python code giving wrong output - python

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

Related

Find the next prime number in Python

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

How to make this recursion function for prime number more efficient

I have this code:
def has_divisors(n, i=2):
"""
Check if a number is prime or not
:param n: Number to check
:param i: Increasing value that tries to divide
:return: True if prime, False if not
"""
if n <= 1:
return False
if i + 1 == n:
return True
if n <= 2 and n > 0:
return True
if n % i == 0:
return False
return has_divisors(n, i + 1)
Which tell if a number is prime or not, problem is that it can check if a number is prime up to +- 1500 after that it enters into maximum recursion depth error. Does anyone has any idea how to make this code more efficient (I don't want completely different code, yes I know recursion is not a good idea for this function but I have to use it)
Thank you!
I actually made it more efficient by just adding one condition:
def has_divisors(n, i=2):
"""
Check if a number is prime or not
:param n: Number to check
:param i: Increasing value that tries to divide
:return: True if prime, False if not
"""
if n <= 1:
return False
if i == n:
return True
if n <= 2 and n > 0:
return True
if i * i > n:
return True
if n % i == 0:
return False
return has_divisors(n, i + 1)
Thanks to everyone who tried to help.
Modifying function from How do I find a prime number using recursion in Python
This should have a maximum recursion dept > 1M
Two improvements:
only goes to sqrt(N), and only checks odd numbers.
def has_divisors(N, i=3):
if N <= 2:
return False
elif N % 2 == 0: # even
return True
elif i * i > N: # tried all divisors to sqrt,
# must be prime
return False
elif (N % i) == 0: # i is a divisor
return True
else: # recursively try the next ( odd) divisor
return has_divisors(N, i + 2)
You don't need to do basic disqualifying tests on every recursion, so to make it more efficient, as you requested, I'd cast it like:
def has_no_divisors(n):
if n <= 2 or n % 2 == 0:
return n == 2
def has_no_divisors_recursive(n, i=3):
if i * i > n:
return True
if n % i == 0:
return False
return has_no_divisors_recursive(n, i + 2)
return has_no_divisors_recursive(n)
By treating 2 as a special case and just test dividing odd numbers, this should also have twice the performance (and half the stack usage) of your revised code.

Project Euler Q #3 Python

I'm really trying to improve my math/coding/problem solving skills by working through the Project Euler problems, and I'm a little stuck on question three. The question is "The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?"
And here's my code thus far
import math
def isPrime(n):
if n > 1:
for i in range(2, n):
if n % i == 0:
return False
else:
return True
else:
return False
def highFactor(m):
factors = []
for i in range(2, int(math.sqrt(m))):
if isPrime(i):
if m % i == 0:
factors.append(i)
print max(factors)
highFactor(13195)
So this obviously was testing on the example they gave since I already know the answer should be 29, but when I run the code it gives me 91. What did I do wrong?
Two issues:
(1) Your isPrime function returns True on the first iteration of the loop. You instead want to finish looping and then return True if you survive the entire loop without ever returning false.
(2) It's possible that an algorithm will have multiple copies of the same prime factor (ie 8 = 2*2*2). You would be better off setting m = m/i and restarting the loop every time. Also, you probably want sqrt(m)+1, since the range function excludes the upper limit.
As mentioned in the comments, your function returns True too early - e.g. if a number is not divisble by 2, it does not mean it will not be divisible by any later number in the range(2, n) - consider 51 = 3 * 17 as a counter-example.
Here is the correct version of your algorithm:
def isPrime(n):
if n > 1:
for i in range(2, n):
if n % i == 0:
return False
return True
else: # if we have a negative number or 0
return False
As others mentioned, there is a faster way to check whether a number is prime; now your function has complexity of O(n), since you check for all numbers up to n; by observation that n = sqrt(n) * sqrt(n) it is enough to check until sqrt(n) + 1
def isPrime(n):
if n > 1:
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
else:
return False
As Austin commented isPrime returns true too early. By moving return True outside of the for loop your function will check each number in range(2, n) before confirming that the number is prime.
Say you were to do isPrime(13) which should return True
On the first pass of the for loop if n % i == 0 would be if 13 % 2 == 0 which is False. Because of the else: return True in the for loop the function will return True and terminate.
To solve the issue you could write isPrime() like:
def isPrime(n):
if n > 1:
for i in range(2, n):
if n % i == 0:
return False
return True
else:
return False

python check prime, stuck at one point

This was the question our teacher gave us:
"One way to determine whether or not a number is a prime number is as follows:
if the number < 2, then return False
if the number is 2, then return True
for each value of i, where i >=2 and i < number:
if i divides the number evenly, then return False
return True"
I've managed to work through most of it, but was stuck when it said 'for each value of i, where i >=2 and i < number:'
how do I write this in code?
if number < 2:
return False
if number == 2:
return True
?????????
if i%2 == 0:
return False
return True
Yo need a loop to check all numbers from 2 to one less than the number being checked. There are better ways to do it (such as only checking up to the square root of the number) but a simplistic algorithm would be:
def isPrime (n):
if n < 2:
return False
for x in range (2, n):
if n % x == 0:
return False
return True
So, in terms of what you need to add to your code:
a loop iterating some variable from two up to one less than the number.
checking modulo with that variable rather than the hard-coded 2.
You will need to start a loop from 2 to the number
for i in range(2,number)
if number%i == 0:
return false
def isprime(num):
#this is the part you are missing
for divider in range(2,num):
if num%divider == 0:
return False
#end of missing part
return not num%2 == 0 or num==2 or num==0
for i in range(0,200):
if isprime(i): print i, isprime(i)

Python loop is escaping a value

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.

Categories

Resources