954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

EVEN Febonacci numbers!!

I am trying generate even febonacii numbers less than four million, but I keep getting negative numbers at some point and eventually it converges to a positive answer, which is obviously wrong. Can anyone please help me out?

#include
#include
void main (void)
{
clrscr();
int f1=1;
int f2=1;
long temp=0;
long total=0;

while (temp<4000000))
{
temp=f1+f2;
f1=f2;
f2=temp;
if (temp%2==0)
{
printf("\n %d",temp);
}
}
getch();
}

Ather14
Newbie Poster
4 posts since Jul 2009
Reputation Points: 10
Solved Threads: 0
 

Major mistakes:

1>Using conio.h its an extinct header man.
2>Using clrscr() its also an extinct call.
3>Problem here is with :

printf("\n %d",temp);

You are printing the long int temp as a signed integer so after it crosses the limit of 32767 it goes on to the negative side.So use use it as:

printf("\n %ld",temp);
csurfer
Posting Pro
568 posts since Jan 2009
Reputation Points: 485
Solved Threads: 88
 

Thanks CsurFer!!

Ather14
Newbie Poster
4 posts since Jul 2009
Reputation Points: 10
Solved Threads: 0
 

u r talking about four million,thats completly out of range for an int declaration...........whether u take long int it will not work,becouse
long int don't have that much range in 32 bit processor..........
but it might work in 64 bit
u may try

oop'stechie
Newbie Poster
4 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

I don't expect febonacci numbers to be negative, so why not use unsigned, it will give you twice the amount you can go.
And %d calls an integer, not a long (so it will only show what an integer would show if it was at that value)
I would also recomend using int main() instead of void main().

u8sand
Junior Poster
131 posts since Dec 2008
Reputation Points: 78
Solved Threads: 15
 

What??! Already the 5th post and nobody has told the OP to use code tags?

To the OP:
http://www.daniweb.com/forums/announcement8-3.html
(read that information please, before making any other post, containing code snippets)

tux4life
Nearly a Posting Maven
2,350 posts since Feb 2009
Reputation Points: 2,134
Solved Threads: 243
 
u r talking about four million,thats completly out of range for an int declaration...........whether u take long int it will not work,becouse long int don't have that much range in 32 bit processor.......... but it might work in 64 bit u may try

the max of a 32 bit unsigned int is 4294967296 or 2147483648 for signed which is more than he needs. the formatting issue is the only problem.

NathanOliver
Veteran Poster
1,084 posts since Apr 2009
Reputation Points: 215
Solved Threads: 189
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You