Click here to Skip to main content
15,891,868 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Java
import java.util.Scanner;


public class Project_Euler_prob_2 
{


	public static void main(String[] args) 
	{
		
		Scanner sc = new Scanner(System.in);
		
		long  a = 1;
		long  b = 2;
		long temp = 0;
		
		long sum = 0;
		
		System.out.println("Enter the value of n");
		long n = sc.nextInt();
		
		for(int i=1;i<=n;i++)
		{
			 temp = a + b;
			 a = b;
			 b = temp;
			 
			 if(b%2 == 0)
			 {
				 sum = sum + b;
				 System.out.println(sum);
			 }
		}
	}

}


What I have tried:

I have tried change just int to long but output not showed well....i don't know different solution..
Posted
Updated 25-Nov-18 23:27pm
v2

1 solution

Your code calculates the sum of the even Fibonacci numbers in the first N Fibonacci numbers. This is not the same as calculating the sum of the even Fibonacci numbers smaller than N.

The 400,000th Fibonacci number is approximately 1083,590. This is larger than any built-in type in Java (or any other language I'm aware of).

Check the condition of your loop; it should be something like:

Java
while (b < n) // don't sum Fibonacci numbers larger than n
{
   …
}
 
Share this answer
 
Comments
OriginalGriff 26-Nov-18 5:33am    
Worse than that - he wants the 4,000,000th Fibonacci number! :OMG:
Daniel Pfeffer 26-Nov-18 6:17am    
Oops! So add a zero to the exponent.
Akash Tawade 26-Nov-18 8:21am    
Thank you @DanielPfeffer
Richard Deeming 27-Nov-18 12:33pm    
"This is larger than any built-in type in Java (or any other language I'm aware of)."

Theoretically, BigInteger (Java[^] / .NET[^]) could cope. :)
Daniel Pfeffer 28-Nov-18 1:24am    
Yes, the standard library for both languages enables this. Given that this is obviously homework (which the OP made a good attempt at solving), I didn't want to confuse the OP with extraneous details.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900