2009-03-29

Cilly C

I'm mostly a Java programmer with a smattering of other languages thrown in. I've recently come to the position that any programmer worthy of the title should be at least comfortable in C/C++. I have long forgotten most of my C so I am now making the effort to relearn it.

I will here relate my experience with my first C program in this curriculum. Since I despise Hello World programs I decided, instead, to write a program to compute and display a Fibonacci sequence. BTW, I love Fibonacci numbers, but that's for another post.

The basic program was simple enough. For those who don't know a Fibonacci sequence consists of all numbers that are the sum of the previous two numbers in the sequence with a starting condition of 0, 1. So one just needs a simple loop to perform that calculation.

Where it got interesting is when I decided I wanted my sequence to be 50 numbers long. One of the properties of Fibonacci numbers is that they get really big really fast (they were originally invented to model rabbit population explosions.) So a little before 50 one gets an integer overflow and nasty twos complement artifacts.

Now, being a Java programmer, I say "no big deal, I'll just use a long." How naive. Silly me, I had forgotten that C doesn't give any guarantees about the size of primitives across implementations. gcc apparently treats a long as a 32 bit integer, just like an int so I still got exactly the same behavior.

Digging through the gcc compiler documentation I found the solution. There's a data type long long int. I love it. At least those C compiler writers have a sense of humor. Anyway it works great... unless of course you want 100 Fibonacci numbers.

Here's my final program.

#include

int main(void) {
int i=0;
long long int fib1=0LL;
long long int fib2=1LL;
long long int temp=0LL;
printf("%d\n",fib1);
printf("%d\n",fib2);
for(i=2;i<93;i++) { //93 is overflow
temp=fib2;
fib2+=fib1;
fib1=temp;
printf("%lld\n",fib2);
}
return 0;
}

No comments:

Post a Comment