Skip to main content
3 of 6
changed return type to save 2 chars
x13
  • 200
  • 8

C, 224 229 227 chars - print n'th fibonacci or 2^n

Golfed up:

#import <Foundation/Foundation.h>
typedef unsigned long long f;f main(int c,char*v[]){f n=strtoull(v[1],(char**)v[2],10)-1;f x=(c>2&&++n==0)?0:1;f y=0;while(n--!=0&&x+y>=x&&x>0){f z=x;c>2?x+=y=z:(x+=y,y=z);}printf("%llu\n",x);}

Readable :

#import <Foundation/Foundation.h>
typedef unsigned long long f;
f main(int c,char*v[]){
    f n=strtoull(v[1],(char**)v[2],10)-1;
    f x=(c>2&&++n==0)?0:1;
    f y=0;
    while(n--!=0&&x+y>=x&&x>0){
        f z=x;
        c>2?x+=y=z:(x+=y,y=z);
    }
    printf("%llu\n",x);
}

If the number exceeds the length of an unsigned long long it will print the highest it can get. Return type is f (unsigned long long) for short code, it does generate 2 compiler warnings and a note but it still compiles!

It also has the option to calculate 2^n because it initially printed that.

Usage :

  • ./fibbin 42 - prints 42'th fibonacci number (267914296)
  • ./fibbin 42 anyInputHere - prints 2^n (4398046511104).

Don't enter values of 0, higher than 93 (fibonacci) or higher than 63 (2^n).

Examples :

  • ./fibbin 1 = 1

  • ./fibbin 2 = 1

  • ./fibbin 3 = 2

  • ./fibbin 4 = 3

  • ./fibbin 42 = 267914296

  • ./fibbin 92 = 7540113804746346429

  • ./fibbin 93 = 12200160415121876738 - this is the highest i can go

  • ./fibbin 94 = should be 19740274219868223167, but it doesn't fit into an unsigned long long so i will print #93

  • ./fibbin 1 bin - 2

  • ./fibbin 2 bin - 4

  • ./fibbin 3 bin - 8

  • ./fibbin 4 bin - 16

  • ./fibbin 42 bin - 4398046511104

  • ./fibbin 62 bin - 4611686018427387904

  • ./fibbin 63 bin - 9223372036854775808 - this is the highest i can go

  • ./fibbin 64 bin - should be 18446744073709551616, but it doesn't fit into an unsigned long long so i will print 0

These tests match the output of wolfram-alpha, due to the heavy calculations wolfram may time out but it generally doesn't.

x13
  • 200
  • 8