Program to find the nth prime number - python

I wrote a code in python to find the nth prime number.
print("Finds the nth prime number")
def prime(n):
primes = 1
num = 2
while primes <= n:
mod = 1
while mod < (num - 1):
ptrue = 'true'
if num%(num-mod) == 0:
ptrue = 'false'
break
mod += 1
if ptrue == 'true':
primes += 1
return(num)
nth = int(input("Enter the value of n: "))
print(prime(nth)
The code looked fine to me, but it returns an error when I run it:
Traceback (most recent call last):
File "C:/Users/AV/Documents/Python/nth Prime.py", line 17, in <module>
print(prime(nth))
File "C:/Users/AV/Documents/Python/nth Prime.py", line 13, in prime
if ptrue == 'true':
UnboundLocalError: local variable 'ptrue' referenced before assignment
It appears to me as if it is trying to say that I am referring to ptrue in the last line even though I am not. What is the problem here... Can anyone help?

how about using Boolean ? and initalize ptrue out of while loop
print("Finds the nth prime number")
def prime(n):
primes = 1
num = 2
while primes <= n:
mod = 1
ptrue = True
while mod < (num - 1):
if num%(num-mod) == 0:
ptrue = False
break
mod += 1
if ptrue == True:
primes += 1
return(num)
nth = int(input("Enter the value of n: "))
print prime(nth)

ptrue is local to your while loop which goes out of scope as soon as the while loop ends. so declare ptrue before the start of your inner while loop

Get rid of ptrue entirely and use else with your inner loop. For example:
while mod < (num - 1):
if num % (num - mod) == 0:
break
mod += 1
else:
primes += 1 # only executes if loop terminates normally, without `break`

You can try this:
#This program finds nth prime number
import math
def is_prime(number):
if number < 2:
return False
if number % 2 == 0:
return False
else:
for i in range(3, number):
if not number % i:
return False
return True
n = input('Enter n: ')
#This array stores all the prime numbers found till n
primes = []
for i in range(100000):
if is_prime(i):
primes.append(i)
if len(primes) == n:
break
print("nth prime number is: " + str(primes[n-1]))

The first part is define a function that calculates the next prime number given any number.
import math
def is_prime(x): # function
for i in range(2,int(math.sqrt(x))+1):
if x%i == 0:
return is_prime(x+1)
return x
For example, is_prime(10) will return 11.
The next step is to write a generator that returns a list of prime numbers.
def get_prime(k): # generator
cnt = 1
n = 2
while cnt <= k:
yield(is_prime(n))
n = is_prime(n) + 1
cnt += 1
For example, get_prime(5) will return [2,3,5,7,11].
The code below can help you test the results.
a = get_prime(50)
lists = list(a)[:]
for idx, value in enumerate(lists):
print("The {idx}th value of prime is {value}.".format(idx = idx+1, value = value))

All answers depends on user input, but here is a simple code to give nth number, no matter how big the n is ....
def isprime(n): # First the primality test
if n<2:
return False
for i in range(2,n):
if n%i==0:
return False
break
else:
return True
def nthprime(n): # then generic code for nth prime number
x=[]
j=2
while len(x)<n:
if (isprime(j)) == True:
x.append(j)
j =j+1
print(x[n-1])

n=int(input('enter n'))
a=[2,3,5,7]
i=3
j=9
while i<n:
flag=0
j=j+2
for k in range(len(a)):
if (a[k]<=int(j**0.5) and j%a[k]==0):
flag=1
break
if flag==0:
a=a+[j]
i=i+1
print(a[n-1])

Try this.
n = int(input())
count=1
u=2
prime=[]
while(count<=n):
temp=0
for i in range(2,u):
if(u%i==0):
temp=1
if(temp==0):
count+=1
prime.append(u)
u+=1
print(prime[-1])

Program to find nth Prime Number.
def nth_Prime(num):
Semi = num*num
Res_1 = [True for i in range(Semi+1)]
prime = 2
while prime*prime <= Semi:
if Res_1[prime] == True:
for i in range(prime*prime, Semi+1, prime):
Res_1[i] = False
prime += 1
Res_2 = []
for i in range(2, Semi+1):
if Res_1[i]:
Res_2.append(i)
return Res_2[num-1]
if __name__ == "__main__":
num = int(input("Enter nth Number: "))
print(nth_Prime(num))

Try this out ,I just made few changes in yours.
Here I am checking for each prime number using all(num%i!=0 for i in range(2,num)) checking its remainder not equal to zero so if it is true for that range (starting from 2 and less than itself) it is a prime and for that all() function helps me later if its a prime I increment the 'p' count and check till 'p' is less than the 'n'(Input Number) so when it equates the condition its the nth prime we are looking for.
n=raw_input("enter the nth prime ")
num=4
p=2
while p <int(n):
if all(num%i!=0 for i in range(2,num)):
p=p+1
num=num+1
print "nTH prime number: ",num-1

Related

How do you find the first N prime numbers in python?

I am pretty new to python, so I don't fully understand how to use loops. I am currently working on a piece of code that I have to find the first N prime numbers.
The result that is desired is if you input 5, it outputs 2, 3, 5, 7, and 11, but no matter what I input for 'max', the output always ends up being 2 and 3. Is there a way to improve this?
max=int(input("How many prime numbers do you want: "))
min=2
while(min<=(max)):
for c in range(2, min):
if min%c==0:
break
else:
print min
min=min+1
You only increment min in the else block, i.e., if min % c is nonzero for all c, i.e., if min is prime. This means that the code won't be able to move past any composite numbers. You can fix this by unindenting min=min+1 one level so that it lines up with the for and else.
number = int(input("Prime numbers between 2 and "))
for num in range(2,number + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
Solution: Get the nth prime number entry. Iterate through each natural numbers for prime number and append the prime number to a list. Terminate the program when length of a list satisfies the user nth prime number entry.
# Get the number of prime numbers entry.
try:
enterNumber = int(input("List of nth prime numbers: "))
except:
print("The entry MUST be an integer.")
exit()
startNumber = 1
primeList = []
while True:
# Check for the entry to greater than zero.
if enterNumber <= 0:
print("The entry MUST be greater than zero.")
break
# Check each number from 1 for prime unless prime number entry is satisfied.
if startNumber > 1:
for i in range(2,startNumber):
if (startNumber % i) == 0:
break
else:
primeList.append(startNumber)
if (len(primeList) == enterNumber):
print(primeList)
break
else:
startNumber = startNumber + 1
continue
Try that :
n = int(input("First N prime number, N ? "))
p = [2]
c = 2
while len(p) < n:
j = 0
c += 1
while j < len(p):
if c % p[j] == 0:
break
elif j == len(p) - 1:
p.append(c)
j += 1
print(p)
Its simple. Check the below code, am sure it works!
N = int(input('Enter the number: ')
i=1
count=0
while(count<N):
for x in range(i,i+1):
c=0
for y in range(1,x+1):
if(x%y==0):
c=c+1
if(c==2):
print(x)
count=count+1
i=i+1
The following code will give you prime numbers between 3 to N, where N is the input from user:
number = int(input("Prime numbers between 2, 3 and "))
for i in range(2,number):
for j in range(2,int(i/2)+1):
if i%j==0:
break
elif j==int(i/2):
print(i)
You can see to check a number i to be prime you only have to check its divisibility with numbers till n/2.

Python3.x Prime Number List with while loop

def prime(upper):
while upper >=2:
for num in range(2, upper + 1):
prime = True
for i in range(2, num):
if (num % i == 0):
prime = False
if prime:
print(num, end=",")
if num == upper: #I think there is a problem here
break
prime(7)
How can I stop this function when it reachs 7 value
PS: I want to execute this codes with while loop.
BTW if you can make it this codes without for-loop please do it for me :)
I appreciate you...
EDIT:
I guess my previous is_prime function is problematic. This way is quicker and works well:(Source)
def is_prime(n):
""""pre-condition: n is a nonnegative integer
post-condition: return True if n is prime and False otherwise."""
if n < 2:
return False;
if n % 2 == 0:
return n == 2 # return False
k = 3
while k*k <= n:
if n % k == 0:
return False
k += 2
return True
You should use this function.
BEFORE EDIT:
I would use the is_prime function from here. You can use another way.
And, I would suggest this code for you:
def is_prime(Number):
return 2 in [Number, 2**Number%Number]
def prime(upper):
print([num for num in range(2, upper + 1) if is_prime(num)])
prime(7)
Output:
[2, 3, 5, 7]
But if you insist on using only while loop, you can modify your prime function as:
def prime(upper):
num = 2
while num <= upper:
if is_prime(num):
print(num, end = ",")
num += 1
Then, output will be:
2,3,5,7,

Python - Prime check and increment

My objective of the below code is
check if entered number is a prime
if not print the next biggest prime
def primetest (num):
for c in range (2, num):
if num % c == 0:
repeattest (num) #not prime? increment number
else :
print (num,"is a prime number")
break
def repeattest (num): # check prime if not increment number by 1
for z in range (2, num):
num = num+1
primetest (num)
if num % z == 0:
num = num+1
else:
print ("Next Prime:", num+1)
break
num = int (input ("enter a number:")) # main code:
for y in range (2, num):
if num % y == 0:
repeattest (num)
else:
print (num,"is a prime number")
break
I think the logic is fine, but not sure why im not getting any output.
Time comlexity of your code is O(N) when it find a number which is prime or not.
There is no pointing on dividing from 2 to len(num)-1. It is enough to loop from 2 to sqrt of the given number. Therefore time complexity reduce to O(n) to O(log(n)).
import math
num = int (input ("enter a number:"))
def primeTest(num):
isPrime = 0
for i in range(2,int(math.sqrt(num)+1)):
if num%i == 0:
isPrime = isPrime + 1
break
if isPrime == 0:
print(num, "is a prime number")
else:
num = num + 1
repeatTest(num)
def repeatTest (num):
isPrime = 0
for i in range(2,int(math.sqrt(num))):
if num%i == 0:
isPrime = isPrime + 1
break
if isPrime == 0:
print("Next Prime: ", num)
else:
num = num + 1
repeatTest(num)
primeTest(num)
The logic which you are using to find if a number if prime seems wrong .
Taking a integer like 9 prints "9 is a prime number" .
And also you are checking for next prime numbers from 2 to Num .
Num being the input , you cant get a number greater than that .
It exits from the loop without even getting in , therefore not printing anything when you are searching for next prime .
You need to change the logic .
write a separate function for checking prime and end the loop when you find the next prime number instead of stopping at num .

Prime Factor Program

Problem
Here is the problem I am trying to solve.
The prime factors of 13195 are 5, 7, 13, 29. What is the largest prime factor of the number 600851475143?
def prime_calc():
num = raw_input("What is the number you want the primes for?")
prim_num = []
x = 2
while num/x > 1:
new_num = num / x
if num % x == 0:
return prim_num.append(x)
elif num % x != 0:
new_num = num/x += 1
return prim_num.append(x)
else:
break
I keep getting an invalid syntax error starting from the bottom up to the fourth line that doesnt like my "+=" operator
This line:
new_num = num/x += 1
should be broken into two lines:
x += 1
new_num = num/x
The statement x += 1 in python doesn't return anything, so you can't use it as part of an expression.
Similarly, the two instances of:
return prim_num.append(x)
Also won't work, since the statement: prime_num.append(x) doesn't return anything.
You need to break this into:
prime_num.append(x)
return prime_num
num=int(input("Please enter number to calculate prime factor"))
k=0
item=[]
if(num%2==0):
prime=2
item.insert(k,prime)
k=k+1
j=3
flag=int(num/2)
while(j<flag and num>2):
if num%j==0:
prime=j
item.insert(k,prime)
k=k+1
num=num/j
j=j+2
else:
j=j+2
if k==0:
print("sorry no prime factor for this number")
else:
print("Please find the largest prime factor below")
print(item.pop())

Prime number check acts strange [duplicate]

This question already has answers here:
How to create the most compact mapping n → isprime(n) up to a limit N?
(29 answers)
Closed 7 years ago.
I have been trying to write a program that will take an imputed number, and check and see if it is a prime number. The code that I have made so far works perfectly if the number is in fact a prime number. If the number is not a prime number it acts strange. I was wondering if anyone could tell me what the issue is with the code.
a=2
num=13
while num > a :
if num%a==0 & a!=num:
print('not prime')
a=a+1
else:
print('prime')
a=(num)+1
The result given when 24 is imputed is:
not prime
not prime
not prime
prime
How would I fix the error with the reporting prime on every odd and not prime for every even?
You need to stop iterating once you know a number isn't prime. Add a break once you find prime to exit the while loop.
Making only minimal changes to your code to make it work:
a=2
num=13
while num > a :
if num%a==0 & a!=num:
print('not prime')
break
i += 1
else: # loop not exited via break
print('prime')
Your algorithm is equivalent to:
for a in range(a, num):
if a % num == 0:
print('not prime')
break
else: # loop not exited via break
print('prime')
If you throw it into a function you can dispense with break and for-else:
def is_prime(n):
for i in range(3, n):
if n % i == 0:
return False
return True
Even if you are going to brute-force for prime like this you only need to iterate up to the square root of n. Also, you can skip testing the even numbers after two.
With these suggestions:
import math
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
Note that this code does not properly handle 0, 1, and negative numbers.
We make this simpler by using all with a generator expression to replace the for-loop.
import math
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
def isprime(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up
# the square root of n for all odd numbers
for x in range(3, int(n**0.5) + 1, 2):
if n % x == 0:
return False
return True
Taken from:
http://www.daniweb.com/software-development/python/code/216880/check-if-a-number-is-a-prime-number-python
def is_prime(n):
return all(n%j for j in xrange(2, int(n**0.5)+1)) and n>1
The two main problems with your code are:
After designating a number not prime, you continue to check the rest of the divisors even though you already know it is not prime, which can lead to it printing "prime" after printing "not prime". Hint: use the `break' statement.
You designate a number prime before you have checked all the divisors you need to check, because you are printing "prime" inside the loop. So you get "prime" multiple times, once for each divisor that doesn't go evenly into the number being tested. Hint: use an else clause with the loop to print "prime" only if the loop exits without breaking.
A couple pretty significant inefficiencies:
You should keep track of the numbers you have already found that are prime and only divide by those. Why divide by 4 when you have already divided by 2? If a number is divisible by 4 it is also divisible by 2, so you would have already caught it and there is no need to divide by 4.
You need only to test up to the square root of the number being tested because any factor larger than that would need to be multiplied with a number smaller than that, and that would already have been tested by the time you get to the larger one.
This example is use reduce(), but slow it:
def makepnl(pnl, n):
for p in pnl:
if n % p == 0:
return pnl
pnl.append(n)
return pnl
def isprime(n):
return True if n == reduce(makepnl, range(3, n + 1, 2), [2])[-1] else False
for i in range(20):
print i, isprime(i)
It use Sieve Of Atkin, faster than above:
def atkin(limit):
if limit > 2:
yield 2
if limit > 3:
yield 3
import math
is_prime = [False] * (limit + 1)
for x in range(1,int(math.sqrt(limit))+1):
for y in range(1,int(math.sqrt(limit))+1):
n = 4*x**2 + y**2
if n<=limit and (n%12==1 or n%12==5):
# print "1st if"
is_prime[n] = not is_prime[n]
n = 3*x**2+y**2
if n<= limit and n%12==7:
# print "Second if"
is_prime[n] = not is_prime[n]
n = 3*x**2 - y**2
if x>y and n<=limit and n%12==11:
# print "third if"
is_prime[n] = not is_prime[n]
for n in range(5,int(math.sqrt(limit))):
if is_prime[n]:
for k in range(n**2,limit+1,n**2):
is_prime[k] = False
for n in range(5,limit):
if is_prime[n]: yield n
def isprime(n):
r = list(atkin(n+1))
if not r: return False
return True if n == r[-1] else False
for i in range(20):
print i, isprime(i)
Your problem is that the loop continues to run even thought you've "made up your mind" already. You should add the line break after a=a+1
After you determine that a number is composite (not prime), your work is done. You can exit the loop with break.
while num > a :
if num%a==0 & a!=num:
print('not prime')
break # not going to update a, going to quit instead
else:
print('prime')
a=(num)+1
Also, you might try and become more familiar with some constructs in Python. Your loop can be shortened to a one-liner that still reads well in my opinion.
any(num % a == 0 for a in range(2, num))
Begginer here, so please let me know if I am way of, but I'd do it like this:
def prime(n):
count = 0
for i in range(1, (n+1)):
if n % i == 0:
count += 1
if count > 2:
print "Not a prime"
else:
print "A prime"
This would do the job:
number=int(raw_input("Enter a number to see if its prime:"))
if number <= 1:
print "number is not prime"
else:
a=2
check = True
while a != number:
if number%a == 0:
print "Number is not prime"
check = False
break
a+=1
if check == True:
print "Number is prime"
a=input("Enter number:")
def isprime():
total=0
factors=(1,a)# The only factors of a number
pfactors=range(1,a+1) #considering all possible factors
if a==1 or a==0:# One and Zero are not prime numbers
print "%d is NOT prime"%a
elif a==2: # Two is the only even prime number
print "%d is prime"%a
elif a%2==0:#Any even number is not prime except two
print "%d is NOT prime"%a
else:#a number is prime if its multiples are 1 and itself
#The sum of the number that return zero moduli should be equal to the "only" factors
for number in pfactors:
if (a%number)==0:
total+=number
if total!=sum(factors):
print "%d is NOT prime"%a
else:
print "%d is prime"%a
isprime()
This is a slight variation in that it keeps track of the factors.
def prime(a):
list=[]
x=2
b=True
while x<a:
if a%x==0:
b=False
list.append(x)
x+=1
if b==False:
print "Not Prime"
print list
else:
print "Prime"
max=int(input("Find primes upto what numbers?"))
primeList=[]
for x in range(2,max+1):
isPrime=True
for y in range(2,int(x**0.5)+1) :
if x%y==0:
isPrime=False
break
if isPrime:
primeList.append(x)
print(primeList)
Prime number check.
def is_prime(x):
if x < 2:
return False
else:
if x == 2:
return True
else:
for i in range(2, x):
if x % i == 0:
return False
return True
x = int(raw_input("enter a prime number"))
print is_prime(x)
# is digit prime? we will see (Coder: Chikak)
def is_prime(x):
flag = False
if x < 2:
return False
else:
for count in range(2, x):
if x % count == 0:
flag = True
break
if flag == True:
return False
return True

Categories