Project Euler #2: Even Fibonacci numbers

  • + 2 comments

    I used Binet's formula, changed to long in C++ and I still get a few timeouts. Any recommendations?

    • + 0 comments

      well this won't give any timeouts but one test case is failing , i think it's because of inaccuracy we get in golden ratio while calculating it for very large term for e.g. the following code will generate 27th term as 37889062373143904 instead of 37889062373143906. rectify it and you will get the correct code :)

      int main(){
          int t; 
          scanf("%d",&t);
          for(int a0 = 0; a0 < t; a0++){
              long n, sum = 0; 
              scanf("%ld",&n);
              long curr_num = 2;
              while(curr_num<=n){
                  sum += curr_num;
                  curr_num = (long)floor((pow(((1 + pow(5 , 0.5)) / 2),3) * curr_num + 0.5));
                  //sum += curr_num;
              }
              printf("%ld \n", sum);
          }
          return 0;
      }
      
    • + 1 comment

      sorry for late advice - store the first fibbonachi numbers in memory and go thrue tests $-)

      import functools
      @functools.lru_cache(maxsize=None)
      def fib(n):
          if n<=2:
              return 1
          else:
              return fib(n-1) + fib(n-2)
      
      
      
      n = int(input().strip())
      s=0
      for i in range(3,n,3):
          _ = fib(i)
          if _<=n:
              s+=_
          else:
              break
              
      print(_)
      

      all works on slow but wise Python

      • + 0 comments

        for i in range(3,n,3) I see what you did there, smart.