Created
June 30, 2015 04:57
フィボナッチ数列をどこまで小さく記述できるか in C ref: http://qiita.com/maekawatoshiki/items/b1cba7600d3dbd634a79
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> | |
int fibo(int x) | |
{ | |
if(x < 2) | |
return 1; | |
else | |
return fibo(x - 2) + fibo(x - 1); | |
} | |
int main() | |
{ | |
int i; | |
for(i = 0; i < 35; i++) | |
{ | |
printf("%d\n", fibo(i)); | |
} | |
return 0; | |
} |
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> | |
int fibo(int x) | |
{ | |
int i, a = 1, b = 1; | |
for(i = 1; i <= x; i++) | |
{ | |
if(i % 2 == 0) | |
a += b; | |
else | |
b += a; | |
} | |
return (i % 2 == 0) ? a : b; | |
} | |
int main() | |
{ | |
int i; | |
for(i = 0; i < 35; i++) | |
{ | |
printf("%d\n", fibo(i)); | |
} | |
return 0; | |
} |
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
// 偶数か奇数かの判定 | |
if(i % 2 == 0) // Cでは、0以外はTrueなので | |
if(i % 2) // にできる。スペースを抜いてBit演算化すると。 | |
if(i&1) // となる。だいぶコンパクトになった。 | |
// { ~ } の消去 | |
// for や if は文が一文のときは{ }を省略できるので。 | |
for(i = 1; i <= x; i++) | |
{ | |
if(i % 2 == 0) | |
a += b; | |
else | |
b += a; | |
} | |
// の用なものは | |
for(i = 1; i <= x; i++) | |
if(i % 2 == 0) | |
a += b; | |
else | |
b += a; | |
// にできる。 | |
// 三項演算子を使えば | |
if(i % 2 == 0) | |
a += b; | |
else | |
b += a; | |
// は | |
(i&1)?(a+=b):(b+=a) | |
// にできる。 | |
// これだけ小さければ、printf に組み込めるかも? | |
// やってみた。 | |
printf("%d\n",(i&1)?(a+=b):(b+=a)); | |
// いいね。 ifがいらなくなったので | |
for(i = 1; i <= x; i++) | |
printf("%d\n",(i&1)?(a+=b):(b+=a)); | |
// となった。 | |
// 関数も取っ払っちゃおう。 | |
#include <stdio.h> | |
int main() | |
{ | |
int i, a=1, b=0; | |
for(i = 1; i <= 35; i++) | |
printf("%d\n",(i&1)?(a+=b):(b+=a)); | |
return 0; | |
} | |
// for 文が無駄なので、 | |
#include <stdio.h> | |
int main() | |
{ | |
int i=35, a=0, b=1; | |
while(i--) | |
printf("%d\n",(i&1)?(a+=b):(b+=a)); | |
return 0; | |
} | |
// とした。 |
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
int main(){int a=0,b=1,i=35;while(i--)printf("%d\n",(i&1)?(a+=b):(b+=a));} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment