Date: Sat, 16 Dec 2000 03:41:29 -0800 (PST)
From: Junaid Siddique <t_jsiddique
Subject: accu-general: an unsigned long internal representation problem
To: accu-general@accu.org

>From Junaid Siddique <t_jsiddique
Replies will be sent to the list (Reply-to: header set)

Hello guys:

Consider the following program that takes an unsigned
integer "n" and returns the nth fibonacci number. 

unsigned long fibonacci(unsigned int n) {
	unsigned long	termn_1 = 1, //(n-1)th term
			termn_2=0,   //(n-2)th term
			termn=1;     // nth term

	unsigned int	count=2;	
	const unsigned long max = 4294967295/2.618; 
// Line 1 : 4294967295/2.618 = 1640552824; 

		if (n == 0 || n==1)
		   return n;			
	        else 
		do {
		   if (termn_2>=max)	
//checks if calculated result is out of range	  		    
 return 4;	//returns error code
		
                    else {
			termn = termn_1 + termn_2;
			termn_2 =termn_1;
			termn_1=termn;
		    }

		} while (count++ < n);

	return termn;
}

If this program is run as is (on MSVC++ 6.0) , it
computes the fibonacci numbers as long as n <= 40. For
n > 40, it returns the error code. Note that
4294967295/2.618 = 1640552824. This is confirmed by
printing the value of max. 

However, If the expression  4294967295/2.618 is
replaced by 1640552824, the same program computes
fibonacci numbers for n <=47. 

I cant come up with an explanation for that. It
appears as if this has to do with the internal
representation of an unsigned long, but I was just
wondering what exactly. 

Comments appreciated.

Junaid

[ACCU mailing list details, see http://accu.org/mailinglists.htm ]


