Advertisement
Haulien

Fibonacci Generator

Oct 30th, 2011
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.19 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.         print "\n\nAmount of digits: " + str(len(str(fib)))
  19.        
  20.        
  21.     except KeyboardInterrupt:
  22.         print ""        #just used to catch ctrl+c (terminate) on unix-systems
  23.  
  24.  
  25.  
  26.  
  27.  
  28.  
  29.  
  30. try:
  31.  
  32.  
  33.     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: "))
  34.  
  35.     start = time.time()
  36.     fib(howMany)
  37.     elapsed = (time.time() - start)
  38.  
  39.  
  40.    
  41.    
  42. except ValueError:
  43.     print "\n\nPlease enter a number\n\n"
  44. except KeyboardInterrupt:
  45.     print ""
  46.     #just used to catch ctrl+c (terminate) on unix-systems
  47.    
  48.    
  49.  
  50. print "\n\nTime elapsed: " + str(elapsed) + "s\n\n"
  51.  
  52.    
  53.  
  54. print "\n\nGoodbye\n\n"
  55.  
  56.  
  57.  
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement