Project Euler #2: Even Fibonacci numbers

Sort by

recency

|

630 Discussions

|

  • + 0 comments

    KOTLIN Code

    fun main(args: Array<String>) {
        val t = readLine()!!.trim().toInt()
    
        for (tItr in 1..t) {
            val n = readLine()!!.trim().toLong()
            createFibonacciSum(n)
        } 
    }
    
    private fun createFibonacciSum(n: Long){
        var left = 0L
        var middle = 1L
        var sum = 0L
        var i = 0
        while(i< n && (middle + left)< n){
            var right = middle + left
            left = middle
            middle = right
            if(right % 2L == 0L) sum += right
            i++ 
        }
        println(sum)
    }
    
  • + 0 comments
    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;
            }
            printf("%ld\n",sum);
    
  • + 0 comments

    a very optimized solution with recursion

    python def fib_sum_even(n, current, nextnum, sum_even): if current>n: return sum_even if current % 2 == 0: sum_even += current return fib_sum_even(n, nextnum, current+nextnum, sum_even)

  • + 0 comments

    include

    include

    using namespace std; int main(){ int n; cin >> n; for (int a = 0; a < n; a++){ long n; cin >> n;

        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;
        }
        cout << sum << endl;
    }
    return 0;
    

    }

  • + 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)