Python - n Prime [duplicate] - python

This question already has answers here:
To find first N prime numbers in python
(30 answers)
Closed 5 years ago.
I’m new to python and I’m trying to figure out how to make a function where you enter a number and it gives you the number prime.
Example: If I enter 6 it returns 13. Since 13 is the 6th prime.
Preferably no modules except ones in standard library,
Thank you

This is what you are looking for:
def nth_prime_number(n):
# initial prime number list
prime_list = [2]
# first number to test if prime
num = 3
# keep generating primes until we get to the nth one
while len(prime_list) < n:
# check if num is divisible by any prime before it
for p in prime_list:
# if there is no remainder dividing the number
# then the number is not a prime
if num % p == 0:
# break to stop testing more numbers, we know it's not a prime
break
# if it is a prime, then add it to the list
# after a for loop, else runs if the "break" command has not been given
else:
# append to prime list
prime_list.append(num)
# same optimization you had, don't check even numbers
num += 2
# return the last prime number generated
return prime_list[-1]
x = nth_prime_number(8)
print(x)

Try this code !
I am also attach the screenshot of the output .
num=int(input("Enter Position : "))
r =1000
count=0
import sys
for a in range(2,sys.maxsize**10):
k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
count=count+1
if(count==num):
print("Prime Number at position " , num , " is " , a)
break

Related

input a integer X and tell if it is a prime [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 last month.
input a integer X and tell if it is a prime.
If it is a prime, output 'Y'
If not, output 'N' and the smallest prime factor.
Here is the program I have tried to write.
X = int(input('enter a integer X:'))
for i in range(2, X):
if X % i == 0:
print('Y')
else:
print('N')
But I would like to print just one time 'Y' or 'N'. And I also do not know how to make the smallest prime factor show on my program result.
Thank you all for helping me
Use any and := walrus operator along with generator like this
This will work for python >= 3.8.
n = int(input("Enter a number : "))
j = 2
if any(((k:=j) and (not n%j)) for j in range(2, int(n**0.5)+1)) :
print(k)
else:
print("prime")
n = int(input("Enter Number:")) # input from user
# ====================================PRIME CHECK==================================== #
flag = 0
for i in range(2,n): # looping to check if number is divisible by other numbers
if n % i == 0:
flag = 1 # setting flag value to 1
print(i) # printing value of i for which n is divisible
break # to exit from the if clause
if flag == 1: # checking if the value of flag is 1 then print it is not prime
print(n, "is not a Prime")
else: # else print prime and the value of n
print(n, "is Prime")

Validate if input number is prime

Trying to write a program that checks if a number is prime.
Wrote the below code, but do not understand why do I have an output of 2 lines:
num = int(input("Provide number to check if prime: "))
if num <=1:
print("Invalid choice, try again")
num = int(input("Provide number to check if prime: "))
for i in range(2,num):
if num% i ==0:
print("Number is not prime")
break
if num %i !=0:
print("Number is prime")
My output is :
Provide number to check if prime: 15
Number is prime
Number is not prime
The sympy.isprime() is a built-in function under the SymPy module and can be utilized for checking of possible prime numbers. It is a direct function and returns True if the number to be checked is prime and False if the number is not prime.
>>> import simpy
>>> sympy.isprime(8)
False
>>> sympy.isprime(11)
True
or else define a function like this
>>> def isPrime(k):
# 1 is not prime number
if k==1:
return False
# 2, 3 are prime
if k==2 or k==3:
return True
# even numbers are not prime
if k%2==0:
return False
# check all numbers till square root of the number ,
# if the division results in remainder 0
# (skip 2 since we dont want to divide by even numbers)
for i in range(3, int(k**0.5)+1, 2):
if k%i==0:
return False
return True
>>> print(isPrime(13))
True
>>> print(isPrime(18))
False
As the first thing, you should remember that 1 isn't a prime number by definition, even if it can't be divided by any other number:
if (num == 1):
print("The number is NOT prime")
else:
for i in range(2, num):
if (num%i == 0): # If the number has a divisor
print("The number is NOT prime")
break
else: # If the for loop ends without reaching any break
print("The number IS prime")
The else branch of a for loop is reached when the loop ends without reaching any break AND the loop executes at least one time.
To better understand my answer, I would suggest to read this.
The error with your solution is caused by the loop printing that the number is prime for each time num%i == 0, so taking num = 6:
6%4 != 0 # The number is prime
6%5 != 0 # The number is prime
As Rajarshi Ghosh suggested, you should know that while programming it's a good idea to use imported functions to do this simple operations, in order to avoid long operations for such a simple job.
If you don't want to use an imported function, I would suggest you to read this article where they explained 6 ways of finding if a number is prime without using functions made by others.
You have issues in output, not only for the case of 15, but also for cases smaller than 1. The following code should work. It has two improvements.
It prints the correct output for 15. The key is to move the else block to align with the for loop.
It prints the correct output for any number smaller than 1, which is not prime. The key is to use the while-break method to get user enter right number until it is bigger than 1.
num = int(input("Provide number to check if prime: "))
while num <=1: #you need to use while loop
print("Invalid choice, try again")
num = int(input("Provide number to check if prime: "))
if num > 1: #only evaluate number is prime or not if it is greater than 1
for i in range(2,num):
if num% i ==0:
print("Number is not prime")
break
else: #to move the `else` block to align with the `for` loop.
print("Number is prime")
break #add a break here
Output:
What is a while loop?
A while loop tests the input condition. Every time the loop finishes, the condition is reevaluated (only evaluate number is prime or not if it is greater than 1). As long as the the number entered is <=1, the loop keeps executing (keep asking users for input).
If you want to just check whether a number is prime or not just do the following:
num = int(input("Provide number to check if prime: "))
flagNotPrime = False
if num > 1:
for i in range(2, num):
if (num % i) == 0:
flagNotPrime = True
break
if flagNotPrime:
print("Number is not prime")
else:
print("Number is prime")
Firstly, numbers that are <= 1 are not prime numbers. Therefore, the above code only proceeds if the num is greater than 1.
Secondly, the code checks if num is exactly divisible by any number from 2 to num - 1. If there is a factor in that range, the number is not prime, so the flag is set to True and the loop is broken using break.
Lastly, outside the loop, if the flag is True then num is not prime.

What's the issue with this 1000th prime number code? [duplicate]

This question already has answers here:
Calculating and printing the nth prime number
(11 answers)
Closed 5 years ago.
count=5 #Nth prime number
i=10 #number to be checked
while (count!=1000): #until its not 1000th
if i%2==0 or i%3==0 or i%5==0 or i%7==0: #to check non prime
i=i+1 #next number initialized
else: #for prime
count=count+1 #move to next position
if count==1000: #if is 1000th position
print i," is 1000th prime." #print prime
I am considering 2,3,5,7 are already known as prime and starting from 10.
It gives "11 is 1000th prime" as output.
There is a logical error somewhere, I guess.
As others have mentioned in comments, your criteria for deciding if a number is prime is very wrong. You're only testing whether it's divisible by the first 4 primes, but this is not sufficient for numbers larger than 120 (121 is divisible by 11, but not any of the smaller primes). You need to check all the primes found previously (look up "Sieve of Eratosthenes").
The other problem is that you're not incrementing i when the number is prime. So once you get to 11, you keep incrementing count, but not i. When count gets to 1000 you print i as the 1,000th prime. Take i = i + 1 out of the if block, it should be done every time.
Also, since even numbers can never be prime (except for 2), you can start with i = 11 and increment it by 2 -- don't waste time checking the even numbers. And then you can take i % 2 == 0 out of the test.
The logic you write to calculate prime number is wrong. I think you can store all prime number you calculated in previous test then test next number by dividing all previous prime number or just test next number simply according to the definition of prime number
In loop, if i == 11, then you will increase counter, however, i won't be increased, so for following loops, you will just test if 11 is the prime number. That's why you print 11 as 1000th number. Actually, you will print 11 as Nth prime number. I think you should always increase i.
143 is 11*13 so its not prime.
Your code would count it as prime because you only check if it can be divided by the first 5 prime numbers.
To resolve your doubt I just multiplied the next to primes 11 and 13.
Hope it helps.
By the way your code is also wrong because it only increments "i" when it match the condition, so when it s always checking:
if 11%2==0 or 11%3==0 or 11%5==0 or 11%7==0:
Solution for your code (doesn't calculate the 1000th prime):
count=5 #Nth prime number
i=10 #number to be checked
while (count!=1000): #until its not 1000th
if i%2==0 or i%3==0 or i%5==0 or i%7==0: #to check non prime
pass #next number initialized
else: #for prime
count=count+1 #move to next position
i=i+1
if count==1000: #if is 1000th position
print i-1," is 1000th prime." #print prime
Solution for your problem:
def is_prime(n):
if n == 2 or n == 3: return True
if n < 2 or n%2 == 0: return False
if n < 9: return True
if n%3 == 0: return False
r = int(n**0.5)
f = 5
while f <= r:
if n%f == 0: return False
if n%(f+2) == 0: return False
f +=6
return True
count=5 #Nth prime number
i=10 #number to be checked
while (count!=8): #until its not 1000th
if not is_prime(i): #to check non prime
pass #next number initialized
else: #for prime
count=count+1 #move to next position
i=i+1
if count==8: #if is 1000th position
print i-1," is 1000th prime." #print prime
Function is_prime(n) got from isPrime Function for Python Language

On python, how can i print up to a certain amount of random numbers from a list of generated numbers? [duplicate]

This question already has answers here:
How can I randomly select an item from a list?
(17 answers)
Closed 8 years ago.
I have it set so the user enters a max input and then the program figures out which numbers are prime and then prints it all to a file. But at the moment it only prints the closest prime number to the upper input. I need it to print 20 random numbers and put them on a file. Also with print (num) 20 times it can print 20 different outputs, but if I add print (num) 20 times it prints the same number 20 times
import random
#Always start at 2
lower = 2
#Take input from the user
upper = int(input("Enter maximum size for prime number to be: "))
for num in range(lower,upper + 1):
if num > 1:
#Prime numbers are greater than 1
for i in range(2,num):
if (num % i) == 0:
break
#End program if number is 0
#Print results
else:
randomprimes =(num)
primes =(random.choice(randomprimes))
import sys
former, sys.stdout = sys.stdout, open('Prime Number Generator Output.txt', 'w')
print (primes)
results, sys.stdout = sys.stdout, former
results.close()
random.choice from the random module returns a random item from a given iterable.
If you want 20 random items from a given list without repeating, use random.sample. (Thanks, Hugh Bothwell)
edit: Wouldn't normally do this, but here's a solution:
import random, math
upper = int(input("Enter maximum size for prime number to be: "))
primes = [x for x in range(2, upper) if x not in [j for i in range(2, math.ceil(math.sqrt(upper))) for j in range(i*2, upper, i)]]
with open("Prime Number Generator Output.txt", "w") as f:
for prime in random.sample(primes, min(len(primes),20)):
f.write(str(prime) + "\n")

How could I check if a number is a prime number? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Simple Prime Generator in Python
First I will prompt user to input any number. Then my code will check whether does the number input by the user is a Prime number not.
Here is my codes:
num = int(raw_input("Input any of the number you like:"))
for x in range(2, int(num**0.5)+1):
if num % x == 0:
print "It is not a prime number"
else:
print "It is a prime number"
But question is I cant seem to get the output for 2 and 3. And when I randomly input any numbers like 134245, the system will output alot of sentences. And I do not know why?
Appreciate any kind souls to help me up :)
import urllib
tmpl = 'http://www.wolframalpha.com/input/?i=is+%d+a+prime+number'
def is_prime(n):
return ('is a prime number' in urllib.urlopen(tmpl % (n,)).read())
you should stop once num % x == 0 is true (no need for further testing) and print 'it is a prime number' only if the loop completed without anything printed before.
A number is prime if it only divides by 1 and itself. A pseudocode follows:
boolean prime = true;
for (int i = 2; i * i <= num; i++)
if (num % i == 0) {
prime = false;
break;
}
if (prime)
println("It is prime!");
else
println("It is not prime!");
Look at your code like this:
num = ...
for x in range(2, int(num**0.5)+1):
print something
The body of the loop is executed at every iteration. That means you're printing something at every iteration, i.e. for each x that you check to see if it's a factor of num, you print. That's not what you should be doing; in order to determine whether a number is prime, you check all possible factors first, then print your result. So you shouldn't be printing anything until after the loop.
But question is I cant seem to get the output for 2 and 3.
You're looping from 2 to ceil(sqrt(n)). For 2 and 3, this is an empty range, hence no iteration happens. Either special-case it or rewrite the code such that it assumes that n is prime and tries to disprove it in the loop.
the system will output alot of sentences.
You're printing on every iteration. Instead, use a boolean flag (or a premature return, if you factor it out into a function) to determine prime-ness and print once, after the loop, based on that prime.
Your code is not structured well-- the algorithm continues to loop all the way up to the top of your range, even if you already know that the number is composite, and it also prints some result on each iteration when it should not.
You could put the logic into a function and return True or False for prime-ness. Then you could just check the result of the function in your if statement.
def is_prime(num):
for x in range(2, int(num**0.5)+1):
if num % x == 0:
return False
return True
num = int(raw_input("Input any of the number you like:"))
if not is_prime(num):
print "It is not a prime number"
else:
print "It is a prime number"
Here are two Python routines for calculating primes. (Hint: Google for Sieve of Eratosthenese):
def pythonicSieve(maxValue):
"""
A Pythonic Sieve of Eratosthenes - this one seems to run slower than the other.
see http://love-python.blogspot.com/2008/02/find-prime-number-upto-100-nums-range2.html
"""
return [x for x in range(2,maxValue) if not [t for t in range(2,x) if not x%t]]
def sieveOfEratosthenes(maxValue):
"""
see http://hobershort.wordpress.com/2008/04/15/sieve-of-eratosthenes-in-python/
"""
primes = range(2, maxValue+1)
for n in primes:
p = 2
while n*p <= primes[-1]:
if n*p in primes:
primes.remove(n*p)
p += 1
return primes

Categories

Resources