Advertisement
BERKYT

Finding sum first 4 000 000 numbers from fibonacci

Nov 26th, 2022
982
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.70 KB | None | 0 0
  1. # Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
  2.  
  3. # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
  4.  
  5. # By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
  6.  
  7.  
  8. def get_fib():
  9.     num_old, num_new = 0, 1
  10.  
  11.     while True:
  12.         num_old, num_new = num_new, num_old + num_new
  13.         yield num_new
  14.        
  15.  
  16. def get_nums():
  17.     nums = []
  18.    
  19.     for num in get_fib():
  20.         if num >= 4_000_000:
  21.             return nums
  22.         if num % 2 == 0:
  23.             nums.append(num)
  24.  
  25.  
  26. if __name__ == '__main__':
  27.     print(sum(get_nums()))
  28.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement