Last active
June 17, 2016 17:52
-
-
Save m4kvn/b579672eeff49a9b8cef5699f1b0b74a to your computer and use it in GitHub Desktop.
フィボナッチ数列を表示するプログラム
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <limits.h> | |
#define INIT_MAXSIZE 200 /* 配列の大きさの初期値 */ | |
/* 大きさnの配列aと配列bを筆算した結果を配列cに格納する */ | |
int add(int* a, int* b, int* c, int n) | |
{ | |
int i, row = 0, buf = 0; | |
for (i = 0; i < n; i++) { | |
if (buf != 0 || a[i] != 0 || b[i] != 0) { | |
row = i; | |
} | |
c[i] = (a[i] + b[i] + buf) % 10; | |
buf = (a[i] + b[i] + buf) / 10; | |
} | |
if (buf != 0) return -1; | |
return row; | |
} | |
/* 配列の中身をrow番目から逆順に表示する */ | |
void printNums(int* a, int row) | |
{ | |
int i; | |
for (i = row; i >= 0 ; i--) { | |
printf("%d", a[i]); | |
} | |
putchar('\n'); | |
} | |
/* 配列のサイズを動的に変更する */ | |
int* resize(int* a, int size) | |
{ | |
int* tmp = calloc(size, sizeof(int)); | |
memmove(tmp, a, sizeof(int) * (size-1)); | |
free(a); | |
return tmp; | |
} | |
/* フィボナッチ数列のn番目を表示する */ | |
int fibo(int n) | |
{ | |
int MAXSIZE = INIT_MAXSIZE; | |
int i, row = 0; | |
int* a = calloc(MAXSIZE, sizeof(int)); | |
int* b = calloc(MAXSIZE, sizeof(int)); | |
int* c = calloc(MAXSIZE, sizeof(int)); | |
b[0] = 1; | |
for (i = 0; i < n-1; i++) { | |
while ((row = add(a, b, c, MAXSIZE)) == -1) { | |
puts("ERROR: NUMBER OVERFLOW! Expand MAXSIZE"); | |
printf("(i = %d, MAXSIZE = %d)\n", i, MAXSIZE++); | |
a = resize(a, MAXSIZE); | |
b = resize(b, MAXSIZE); | |
c = resize(c, MAXSIZE); | |
} | |
memcpy(a, b, sizeof(int) * MAXSIZE); | |
memcpy(b, c, sizeof(int) * MAXSIZE); | |
} | |
printf("[%d: SIZE(%d)] ", n, MAXSIZE); | |
printNums(b, row); | |
free(a); | |
free(b); | |
free(c); | |
return 0; | |
} | |
int main(void) | |
{ | |
fibo(10000); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment