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> | |
static unsigned int fib(unsigned int param) | |
{ | |
if (param < 0) { | |
return 0; | |
} | |
if (param == 1 || param == 2) { | |
return 1; | |
} | |
return fib(param - 1) + fib(param - 2); | |
} | |
int main(int argc, char *argv[]) | |
{ | |
// No Error Processing | |
printf("%d", fib(atoi(argv[1]))); | |
} |
fib(param) + fib(param - 1) と本番で書いてしまった。。(※) なんで気付かなかったんだろう(涙
(※)無論、無限ループになる
[ Update January 31st 0:35 JST by mumumu ]
勿論for文でも書ける。こちらの方がスタックを使わない。
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 <assert.h> | |
static unsigned int fib(int param) | |
{ | |
assert(param > 0); | |
int f1, f2, f3 = 0; | |
int i; | |
for (i = 1; i <= param; i++) { | |
if (i == 1 || i == 2) { | |
f1 = 0; | |
f2 = 1; | |
} | |
f3 = f2 + f1; | |
f1 = f2; | |
f2 = f3; | |
} | |
return f3; | |
} | |
int main(int argc, char *argv[]) { | |
// No Error Processing | |
printf("%u", fib(atoi(argv[1]))); | |
} |