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
Related
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.
A prime number is a number that is only evenly divisible by itself and 1.
For example, the number 5 is prime because it can only be evenly divided by 1
and 5. The number 6, however, is not prime because it can be divided evenly
by 2 and 3.
Write a Boolean function named is_prime which takes an integer as an argument
and returns true if the argument is a prime number, or false otherwise. Use
the function in a program that prompts the user to enter a number and then
prints whether the number is prime.
This is the PYTHON code I have put in, but it tells me that it is wrong. I've tried but can't get it.
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
You almost got it. break in wrong place and can't have (and don't want/need) two else clauses:
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
You need to sort out the two else statements, and also change the algorithm so that it only prints num is a prime number if all the iterations of the for loop fail
if num < 2: # catch 1 and anything less than zero
print(num, "is not a prime number")
else:
prime = True
for i in range(2, num):
if num%i == 0:
print(num, "is not a prime number")
print(i,"times",num//i,"is",num)
prime = False
break
if prime:
print(num,"is a prime number")
I would put this in an isPrime function. You only need to check factors up to the square root of the number.
Edit: I see in your question you mentioned this, you just need to modify this code to return True or False
def isPrime(num):
if num < 2:
return False
for i in range(2,num):
if num%i==0:
return False
return True
Output
0 is not a prime number
1 is not a prime number
2 is a prime number
3 is a prime number
4 is not a prime number
2 times 2 is 4
5 is a prime number
6 is not a prime number
2 times 3 is 6
7 is a prime number
8 is not a prime number
2 times 4 is 8
9 is not a prime number
3 times 3 is 9
I took some time to develop a quick but accurate is_prime function in Python. Here it is:
from math import sqrt # you can just import math, but I only use sqrt
def is_prime(n):
if n<0:
n*=-1
if n<2:
return False
for i in range(2,int(sqrt(n))+1): # remember to fix sqrt to math.sqrt if you changed the
if n%i==0: # import to import math instead of from math import sqrt
return False
return True
Explanation:
If x is prime then -x is prime. So I just make the number positive with
if n<0:
n*=-1
0 is composite (it has the factors 1, 2, 3, 4, 5, ...) and 1 is neither, and neither of those are prime, and since n>-1 (because it was absolute valued) the condition n<2 will suffice.
if n<2:
return False
After that, I loop from 2 to int(math.sqrt(n))+1. That's just convert math.sqrt(n) into an int, and then add 1. The reason for math.sqrt is that n can only have factors until its square root (and also itself). The +1 is for keeping the range in bounds if the int() made it less than it was before.
for i in range(2,int(math.sqrt(n))+1):
if n%i==0:
return False
In the loop, I check if i (the loop counter) is divisible into n. If it is, that means n has a factor that isn't 1 (it started from 2) or itself (it ends at the square root of itself, and 1 is not an exception because that was fixed with the if n<2 condition). At that point, it returns False.
If n gets through all of those checks, it is prime.
This is my code:
a=int(input("Enter a number: "))
i=2
p=[]
while i<=a-1:
p.append(a%i)
i=i+1
if 0 not in list(p):
print(a, "is a prime")
else:
print(a, "is not a prime")
Write a script that determines whether or not a user-inputted number is a prime number and prints "The number that you inputted is a prime number" or "The number that you inputted is not a prime number" depending on what your script finds.
I have code that is failing some of the test cases and I'm not sure why. I see some answers on here that involve calculate the sqrt, but I don't understand why that'd be beneficial.
num= int(input())
if num == 0 or num ==1:
print('The number you inputted is not a prime number.')
while num < 0:
break
if num > 0:
for i in range(2,num):
if num%i==0:
print('The number you inputted is not a prime number.')
break
else:
print('The number you inputted is a prime number.')
break
The code is always right when I try it with a few test cases, but it isn't passing my homework assignment.
Your logic is wrong; you should break only if the condition evaluates to True, since you need to test all numbers up to num ** 0.5 (num in your code). 9 is an example of a non-prime number that your code evaluates as prime.
You want something like this:
prime = True
if num > 0:
for i in range(2,num):
if num % i == 0:
prime = False
break
if prime:
print(f'{num} is a prime number.')
else:
print(f'{num} is not a prime number.')
By setting prime to True at the start and changing it to False only if a factor is found, we can tell, after evaluation of the condition for all the values of i, if the number is prime.
The problem occurs in the logic below:
for i in range(2,num):
if num%i==0:
print('The number you inputted is not a prime number.')
break
else:
print('The number you inputted is a prime number.')
break
To see where the issue occurs, try using your code to check if 9 is prime.
Your for loop does the following:
i = 2
if num % i == 0, not prime, break.
else, prime, break.
This means that your for loop is guaranteed to stop at i==2.
In other words, your definition for a prime number, according to this algorithm is 'any odd number'.
To fix this, you need to find a way to allow the loop to iterate between all the remaining possible divisors, without breaking after the first iteration.
I'm going to stop there, to give you a chance to see if you can figure the rest out yourself. If you can't make any progress, let me know, and I'll give another hint.
My assignment is
Create a program that checks whether a number is a prime number. The display should include whether or not the number is prime and a list of the number’s factors.For numbers that are not prime, also include the number of factors for that number.
I have the code
while choice.lower() == "y":
def is_prime_number(x):
if x >= 2:
for y in range(2,x):
if not ( x % y ):
return False
else:
return False
return True
for i in range(int(input("Please enter an interger between 1 and 5,000: "))):
if is_prime_number(i):
prime_numbers += 1
print (i)
print (str(prime_numbers) + " is a prime number.")
the output i get is
Please enter an interger between 1 and 5,000: 22
2
3
5
7
11
13
17
19
8 is a prime number.
Continue (y/n)?:
I need the output to be the factors of that number. Please help i am a begginer
Obviously, you can't just return False as soon as you find a factor if you're supposed to be counting the number of factors. Instead, you need to increment some count of factors and keep going through the loop:
for y in range(2,x):
if not ( x % y ):
factors += 1
Of course you also need code that starts off with factors = 0.
Also, you can't just return True for prime and False for composite; you have to return the number of factors as well. And, since you're no longer returning early as soon as you find a factor, you can't just return True at the end; you need to decide whether the number is prime or not based on the number of factors you've found.
More importantly, you need to return the number of factors, either instead of or in addition to returning whether the number is prime. Maybe you can just return factors. Although you need to figure out what to do about 0 and 1 now; the existing else: return False doesn't make any sense with that.
And you probably want to change your function name from is_prime_number to, say, count_factors.
And then, finally, you need to change your main loop to do something like this:
factors = count_factors(i)
if not factors: # and maybe some other condition for 0 and 1?
print(i, 'is prime')
prime_numbers += 1
else:
print(i, 'has', factors, 'factors')
Hopefully this is enough for you to fill in the rest yourself.
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