0

Possible Duplicate:
Find out 20th, 30th, nth prime number. (I’m getting 20th but not 30th?) [Python]
Fastest way to list all primes below N in python

prime numbers :

P=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, …] 

fibonacci numbers :

F=[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …] 

i want the user to give a random number between (1,100000) and the program to summarize the result (F[n]+P[n])for example if n=3 F[3]+P[3]=7+2=9

i have written the following code :

import math
def F(n):
    return int(((1+math.sqrt(5))**n-(1-math.sqrt(5))**n)/(2**n*math.sqrt(5)))
L=[]
L.append(2)
L=[]
for n in range(2, 10000):
    for x in range(2, n):
        if n % x == 0:
            break
    else:
        # loop fell through without finding a factor
        L.append(n)

while True:
    x = raw_input().strip()
    if x == "END" or x == "end":
        break
    else:
        num = int(x)
        print F(num)+L[num]

it easy for me to find the Fib numbers just from the def F(n) ,but creating the prime numbers list is really a headache cause as the numbers increase it take some time for the list to be created,and making almost impossible to reach the n into those huge numbers..i tried to make a def not to creating the list butjust calculating the prime number just for the n provided by the user.any ideas??

thank you in advance!

Community
  • 1
  • 1
Giorgis3
  • 221
  • 1
  • 8
  • 3
    The question essentially boils down to http://stackoverflow.com/questions/1995890/find-out-20th-30th-nth-prime-number-im-getting-20th-but-not-30th-python – NPE Jan 03 '13 at 21:30
  • 3
    Algorithms to generate prime numbers are older than computers. Did you do any research? – Phil Frost Jan 03 '13 at 21:33
  • Use the [Sieve of Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) to get a list of primes. It's a very fast and simple algorithm to implement. – Marcus Andrews Jan 03 '13 at 22:14

1 Answers1

1

For Prime Numbers, there are several primality tests that you can implement. I like the naive methods, checking up to sqrt(n), there is also the Sieve of Erathostenes as Marcus Stuhr pointed out. You can optimize it a little bit if you check only the primality of odd numbers.

iferminm
  • 1,841
  • 17
  • 32