Advertisement
makispaiktis

Problem 6 - Primes in Fibonacci sequence

Jul 5th, 2021 (edited)
1,099
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None | 0 0
  1. # Function 1 - Find Fibonacci numbers given the number of terms
  2. def fibonacciTerms(nTerms):
  3.     if nTerms <= 0 or nTerms != int(nTerms):
  4.         print("Error while using function '" + fibonacciTerms.__name__ + "'")
  5.         return -1000
  6.     if nTerms == 1:
  7.         return [1]
  8.     elif nTerms == 2:
  9.         return [1, 2]
  10.     else:
  11.         terms = [0 for i in range(nTerms)]
  12.         terms[0] = 1
  13.         terms[1] = 2
  14.         for i in range(2, len(terms)):
  15.             terms[i] = terms[i-1] + terms[i-2]
  16.         terms2 = [str(terms[i]) for i in range(len(terms))]
  17.         terms2 = ", ".join(terms2)
  18.         print("First " + str(nTerms) + " Fibonacci terms are: " + terms2)
  19.         return terms
  20.  
  21. # Function 2 - Find the primes between 1 and a limit
  22. def findPrimes(limit):
  23.     primes = [2, 3]
  24.     for n in range(4, limit+1):
  25.         isPrime = True
  26.         for prime in primes:
  27.             if n % prime == 0:
  28.                 isPrime = False
  29.                 break
  30.         if isPrime:
  31.             primes.append(n)
  32.     return primes
  33.  
  34. # FUNCTION 3 - Find the primes in the first "nTerms" Fibonacci terms
  35. def primesInFibonacci(nTerms):
  36.     terms = fibonacciTerms(nTerms)
  37.     limit = max(terms)
  38.     primes = findPrimes(limit)
  39.     print()
  40.     for i in range(len(terms)):
  41.         for prime in primes:
  42.             if terms[i] == prime:
  43.                 print("* " + str(terms[i]) + " (index " + str(i+1) + ") is prime")
  44.  
  45.  
  46. # MAIN FUNCTION
  47. nTerms = 25
  48. primesInFibonacci(nTerms)
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement