Saturday, June 20, 2009

Solutions to second Project Euler

long* fib = new long[3];
fib[0] = 1;
fib[1] = 2;
long total = 0;
while(true) {
fib[2] = fib[0]+fib[1];
fib[0] = fib[1];
fib[1] = fib[2];
if(fib[2]>=1000000)
break;
if(fib[2]%2==0)
total+=fib[2];
}
System.out.println(total);

------

Another solution:

public class Problem2 {
public static void main(String[] args) {
int fib1 = 0;
int fib2 = 0;
int curFib = 1;
int sum = 0;
while(curFib < 1000000){
if(curFib % 2 == 0){
sum += curFib;
}
fib1 = fib2;
fib2 = curFib;
curFib = fib1 + fib2;
}
System.out.println("Solution to problem 2 = " + sum);
}
}

No comments: