I am new to Python. I am using python 2.7.3 and I have written a small function to check if the given number is prime or not.
The code is as follows -
#!/usr/bin/python2.7
def isprime(n):
if n == 1:
print("1 is neither Prime nor Composite.")
return False
for x in range(2, n):
if n % x == 0:
print("{} equals {} x {}".format(n, x, n // x))
return False
else:
print("{} is a prime number".format(n))
return True
for n in range(1, 5):
isprime(n)
And the output is -
1 is neither Prime nor Composite.
3 is a prime number
4 equals 2 x 2
Why is it escaping 2. I tried debugging as well but its simple bypassing 2.
Thanks.
Think about the case where n == 2:
def isprime(n):
if n == 1: # nope
...
for x in range(2, n): # here we go
So what actually happens?
>>> range(2, 2)
[]
Nothing; you are iterating over an empty range.
Also, you have a logic error - you return True if the first value in range(2, n) (i.e. 2) isn't an integer divisor of n - you claim than any odd number is prime:
>>> isprime(9)
9 is a prime number
True # what?!
If you dedent the last three lines by one level, it fixes both issues:
def isprime(n):
if n == 1:
print("1 is neither Prime nor Composite.")
return False
for x in range(2, n):
if n % x == 0:
print("{} equals {} x {}".format(n, x, n // x))
return False
else:
print("{} is a prime number".format(n))
return True
(alternatively, leave out the else and dedent the last two lines a further level). This gives me:
>>> isprime(9)
9 equals 3 x 3
False
>>> isprime(2)
2 is a prime number
True
If n is 2, then on the line for x in range(2, n): the range(2, 2) will return an empty list.
Related
I have to print nth prime palindrome number with the help of this program, where n is number given by the user but I have a problem in this program, as it is taking much time to print the answer.
n=int(input())
l=[]
for i in range(1,1000000):
y=True
if str(i)==str(i)[::-1]:
if i>=2:
for j in range(2,i):
if i%j==0:
y=False
break
if y:
l.append(i)
print("Your Prime Palindrome Number Is:",l[n-1])
How can I make this code time efficient?
The first part of this code is not specific to this question. It's a general purpose strategy for testing prime numbers. It's faster than sympy.isprime() for values lower than ~500,000 (Python 3.11.1 on Intel Xeon) after which the sympy version betters this implementation.
from math import sqrt, floor
def isprime(n):
if n < 2:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
for i in range(5, floor(sqrt(n))+1, 6):
if n % i == 0 or n % (i + 2) == 0:
return False
return True
Now you need something to test for a palindrome. This function will return True if the string representation of the object is palindromic.
def ispalindrome(o):
return (_ := str(o)) == _[::-1]
And this is the main part of the program. As 2 is the only even prime number, let's treat that as a special case. Otherwise start with 3 and just test subsequent odd numbers.
N = int(input('Enter value for N: '))
if N > 0:
if N == 1:
print(2)
else:
p = 3
while True:
if isprime(p) and ispalindrome(p):
if (N := N - 1) == 1:
print(p)
break
p += 2
Sample output:
Enter value for N: 11
313
I have a function that takes a number (for example, 5) and returns the first prime number after the input number (in this case, it would be 7).
This is my code:
def prime(n):
np=[]
isprime=[]
for i in range (n+1,n+200):
np.append(i)
for x in range(2,199):
for j in np:
if x%j!=0:
isprime.append(x)
return min(isprime)
However, this code doesn't work (it always returns 2). Where is the mistake?
You have a few mistakes, most notably np is clearly meant to be the potential primes (it starts at n+1 which is the first potential number that fits your critera "the first prime number after the input number"), and yet you add x to your prime list, which is from range(2,199), you should be using:
isprime.append(j)
Your primality test is also the wrong way round as a result, you should be using:
j % x != 0
Lastly, you can't append a number if that condition is true in one case, it has to be true in all cases (where x is an integer which satisfies 2 <= x < j), because of this you should switch your second set of for loops around (the x loop should be the inner loop), and you should also only loop up to j-1 (the number being tested). Additionally, you should instead choose to not add an item if j % x == 0:
for ...:
val_is_prime = True
for ...:
if j % x == 0:
val_is_prime = False
break
if val_is_prime:
isprime.append(j)
This results in the following code:
def prime(n):
np=[]
isprime=[]
for i in range (n+1,n+200):
np.append(i)
for j in np:
val_is_prime = True
for x in range(2,j-1):
if j % x == 0:
val_is_prime = False
break
if val_is_prime:
isprime.append(j)
return min(isprime)
And test run:
>>> prime(5)
7
>>> prime(13)
17
>>> prime(23)
29
Note that there's several other efficiency improvements that could be made, but this answer focuses on the mistakes rather than improvements
Try this one, the most pythonic and clear way to do this that I found (but probably not the most efficient):
def is_prime(x):
return all(x % i for i in range(2, x))
def next_prime(x):
return min([a for a in range(x+1, 2*x) if is_prime(a)])
print(next_prime(9))
https://www.geeksforgeeks.org/python-simpy-nextprime-method/
from sympy import *
# calling nextprime function on differnet numbers
nextprime(7)
nextprime(13)
nextprime(2)
Output:
11 17 3
This code working.
def prime(n):
next_prime = n + 1
prime = True
while True:
for i in range(2, next_prime):
if next_prime%i ==0:
prime = False
break
if prime:
return next_prime
else:
next_prime = next_prime + 1
if next_prime % 2 == 0:
next_prime = next_prime + 1
prime = True
if __name__=="__main__":
print(prime(5))
Here is one working sample.
inputNumber = int(input("Enter number to find next prime: "))
def nextPrime(inputNum):
for nextNumToChk in range(inputNum+1, inputNum +200):
if nextNumToChk > 1:
# If num is divisible by any number between 2 and val, it is not prime
for i in range(2, nextNumToChk):
if (nextNumToChk % i) == 0:
break
else:
#found the prime
return nextNumToChk
result = nextPrime(inputNumber)
print "Next Prime is : ",result
Output:-
Enter number to find next prime: 5
Next Prime is : 7
def is_prime(n):
# Corner case
if n <= 1:
return False
# Check from 2 to n-1
for i in range(2, n):
if n % i == 0:
return False
return True
def first_prime_over(n):
prime_number = (i for i in range(n) if is_prime(i))
try:
for i in range(0,n):
(next(prime_number))
except StopIteration:
prime_number_next = (i for i in range(n,n+1000) if is_prime(i))
print(next(prime_number_next))
first_prime_over(10)
Try this one:
def find_next_prime(n):
return find_prime_in_range(n, 2*n)
def find_prime_in_range(a, b):
for c in range(a, b):
for i in range(2, c):
if c % i == 0:
break
else:
return c
return None
def main():
n = int(input('Find the next prime number from: '))
print(find_next_prime(n+1))
if __name__ == '__main__':
main()
n = int(input("Enter a number"))
while True:
n+=1
for x in range(2,n):
if n%x==0:
break
else:
print("next prime number is",n)
break
Still relatively new to Python and I currently have one function that identifies prime numbers as a bool of true or false. If the input value is prime then I will have a second function identify the next prime number after it. Here is what I have so far:
def is_prime(n):
>if n in range(0, 2):
>>n = False
>for i in range(2, n):
>>if n % i == 0:
>>>n = False
>>else:
>>>n = True
>return n
def find_next_prime(n):
*Use the first function is_prime to run this second function*
Try this :
def find_next_prime(n):
n += 1
while not is_prime(n):
n += 1
return n
def is_prime(n):
if n in range(0, 2):
return True
for i in range(2, n):
if n % i == 0:
return False
return True
def find_next_prime(n):
if is_prime(n):
print("{} is prime".format(n))
n += 1
while not is_prime(n):
n += 1
print("{} is next prime".format(n))
else:
print("{} is not prime".format(n))
You can then run it
find_next_prime(4) \\ output --> 4 is not prime
find_next_prime(53) \\ output --> 53 is prime \n 59 is next prime
I have written the below code in python to print out prime numbers but its giving output like:
3,5,7,**9**,11,13,**15**,17,19,**21**,23,25............99
below is the code:
def isprime(n):
if n == 1:
return False
for x in range(2, n):
if n % x == 0:
return False
else:
return True
def primes(n = 1):
while(True):
if isprime(n): yield n
n += 1
for n in primes():
if n > 100: break
print(n)
You are returning True after the number fails to be divisible by one number. You need to return true after you have checked all the numbers. Instead, you should write
def isprime(n):
if n == 1:
return False
for x in range(2, n):
if n % x == 0:
return False
return True
One other note: if you are testing for prime numbers, you only need to test up to the square root of the number. If the number is not divisible by any numbers less than its square root, then it is also is not divisible by any that are greater and thus must be prime. This will help make your code more efficient.
Your isprime function says:
for x in range(2, n):
if n % x == 0:
return False
else:
return True
This means that on the first iteration (when x==2), if n%x is not zero, it will return True. So it will return True for any odd number (above 1, which you skipped).
Instead, you want to return True if none of the numbers in the loop were factors.
for x in range(2, n):
if n % x == 0:
return False
# the loop finished without returning false, so none of the numbers was a factor
return True
I am starting out in Python and have a question about the following piece of code:
def prime2(n):
n = eval(input("What is your number? "))
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
else:
return True
So when True is returned, n is prime. Now is there a way to list all the values of n for which the if statement is true?
Since there is an infinite amount of prime numbers, no. However, you can list all primes in a certain interval:
foo = [x for x in range(1000) if prime2(x)]
This gives you a list of all primes in the interval 0 to 1000.
Edit: Why do you have n as parameter to your function, and then read it as input from the user? This discards the argument that was passed to the function. Input from the user should be outside of that function. The script could look like this:
def prime2(n):
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
max = int(input("What is your number? "))
print [x for x in range(max) if prime2(x)]
Edit2: Fixed the code of prime2 according to #rmflow's comment to the question.
if you need a list of all values when n is a prime then you need a prime number generator. An example (not effectuve though) based on your prime2 function:
import math
def prime2(n):
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
def prime_generator():
n = 1
while True:
n += 2
if prime2(n):
yield n
primes = prime_generator()
for prime in primes:
print prime
will print prime numbers until break