Project Euler #2: Even Fibonacci numbers

Sort by

recency

|

626 Discussions

|

  • + 0 comments

    every even fibinoci number follows a pattern {2,8,34,144} if you look at 8 it is 2*4+0, 34 it is 8*4+2 , 144 it is 34*4+8

    n = int(input().strip()) prev=0 i=2 s=0 tenp=0 while i<=n: s+=i temp=i i=i*4+prev prev=temp print(s)

  • + 0 comments
    public class Solution {
    
            public static void main(String[] args) {
                    Scanner in = new Scanner(System.in);
                    int t = in.nextInt();
    
                    for(int a0 = 0; a0 < t; a0++){
                            long n = in.nextLong();
                            long sum = 0;
                            long x1=1, x2=2;
    
                            while(x2 <= n){
                                    if(x2 % 2 == 0){
                                            sum += x2;
                                    }
    
                                    long next = x1 + x2;
                                    x1 = x2;
                                    x2 = next;   
                            }
                            System.out.println(sum);
                    }
            }
    }
    
  • + 0 comments

    couple hints: 1. don't compute all fibonacci numbers, the even ones are sufficient 2. store a fine selection of even fibonacci numbers and their pre sums for later reference 3. you can even speed up the search for the matching even fibonacci number by using a matching exponential factor and some log functions

  • + 0 comments

    import java.io.; import java.util.; import java.text.; import java.math.; import java.util.regex.*;

    public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
       for(int a0 = 0; a0 < t; a0++){
            long n = in.nextLong();  // Read the limit N for this test case
            long sum = 0;
    
            // Starting the Fibonacci sequence
            long a = 1, b = 2;
    
            // Calculate the sum of even Fibonacci numbers not exceeding N
            while (b <= n) {
                if (b % 2 == 0) {
                    sum += b;
                }
    
                // Generate the next Fibonacci number
                long next = a + b;
                a = b;
                b = next;
            }
    
            // Output the result for this test case
            System.out.println(sum);
        }
    
        in.close(); 
    }
    

    }

  • + 0 comments

    Easier than #1