Advertisement
Haulien

Fibonacci Generator

Oct 30th, 2011
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.11 KB | None | 0 0
  1. import time
  2.  
  3. def fib(n):
  4.     try:
  5.        
  6.         if n < 2:
  7.             return n
  8.         prev = 1
  9.         fib = 1
  10.         for num in range(2, n):
  11.             prev, fib = fib, fib + prev
  12.             #print str(fib) + ", " #remove the hash at the start of this if you want to print each number after generation
  13.        
  14.        
  15.         print "\n\nFibonacci " + str(n) + ": \n\n" + str(fib)
  16.        
  17.        
  18.        
  19.     except KeyboardInterrupt:
  20.         print ""        #just used to catch ctrl+c (terminate) on unix-systems
  21.  
  22.  
  23.  
  24.  
  25.  
  26.  
  27.  
  28. try:
  29.  
  30.  
  31.     howMany = long(raw_input("How many fibonacci numbers would you like generated?\nA Max of 100000 is recommended!\nAnything larger can freeze your system until it is generated\n\nInput your number: "))
  32.  
  33.     start = time.time()
  34.     fib(howMany)
  35.     elapsed = (time.time() - start)
  36.  
  37.  
  38.    
  39.    
  40. except ValueError:
  41.     print "\n\nPlease enter a number\n\n"
  42. except KeyboardInterrupt:
  43.     print ""
  44.     #just used to catch ctrl+c (terminate) on unix-systems
  45.    
  46.    
  47.  
  48. print "\n\nTime elapsed: " + str(elapsed) + "s\n\n"
  49.  
  50.    
  51.  
  52. print "\n\nGoodbye\n\n"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement