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)
Related
def isPrime(n):
if n>1:
for i in range(2,n):
if (n % i==0):
return False
else:
return True
else:
return False
This code worked in most cases, but when input n=133, it returned True as output. Please show me the error.
Please note that your code could return True in the first iteration of the loop, you need to check for the other values.
Let's see how your loop works.
For value such as 3 your loop will have n%i check i.e. 3%2 which won't satisfy the condition. So it will return true.
But for value such as 9. Loop will check 9%2=0 which again doesn't satisfy the condition and returns True.
So use something like.
def isPrime(n):
if n>1:
for i in range(2,n):
if (n % i==0):
return False
else:
x=False
return x;
else:
return False
So I ran this and it seems this function will return True for any odd number because it returns false on the first iteration, which is checking if it's divisible by 2. Overall, your function is pretty much wrong, here is how I would approach it.
def isPrime(n):
div = True
for i in range(2,int(n**0.5)):
if n%i==0:
div = False
break
return div
Here what I did was I only checked prime factors upto the square root of the number (because if a number has a prime factor greater than its square root(but not the number itself), it must also have a prime factor less than its square root, so we do not need to check further), and I exited from the loop whenever even once it was divisible by something. I checked and it's working correctly.
The problem with your loop is that when you are iterating through the for loop, it always returning either True or False. To prevent that, what you should create a counter which changes its value accordingly.
def PrimeChecker(n):
if n < 1:
return f'{n} is less than 1. So, not prime' # You can add this if you
# want.
else:
for i in range(2, n): # The main loop
counter = True # The counter
if n % i == 0: # If it becomes divisible....
counter = False # Counter becomes false.
break # Break out of loop
return counter # Return False or True
Hope that helped :)
Most efficient Primechecker program :)
from math import sqrt
def checkprime(x):
if x > 2 and x % 2 == 0:
return False
elif x < 2:
return False
else:
for i in range(2, int(sqrt(x)) + 1):
if x % i == 0:
return False
return True
return False
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.
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 started getting back to python coding and realized I couldn't quite figure this out. I'm trying to code a prime number function. Could someone help with this?
Here is my code:
def is_prime(x):
a = True
for n in range(2, x-1):
while n < x:
n+=1
if x % n == 0:
a = False
elif n < 2:
a = False
else:
a = True
break
break
return a
If anyone has an idea on what I'm doing wrong, please let me know. A month ago I tried this and couldn't get the logic down. I think I was stumped and didn't ever ask for help... Also, how long do you think I should try to do this for before I ask for help on average?
As, it has been said, you can optimize the code by just checking the odd numbers and iterating upto the sqrt of the num
import math
def isPrime(num):
if(num==1):
return False
if(num==2):
return True
if(num%2==0):
return False
i = 3
while(i<math.sqrt(num)+1):
if num%i==0:
return False
i += 2
return True
#do the inputs and check if isPrime
#print(isPrime(2))
using your code, and focusing on code structure:
def is_prime(x):
# function contents must be indented
if x == 0:
return False
elif x == 1:
return False
# your base cases need to check X, not n, and move them out of the loop
elif x == 2:
return True
for n in range(3, x-1):
if x % n == 0:
return False
# only return true once you've checked ALL the numbers(for loop done)
return True
adding some optimizations:
def is_prime(x):
if x <= 1:
return False
if x == 2:
return True
for n in range(3, x**(0.5)+1, 2): # this skips even numbers and only checks up to sqrt(x)
if x % n == 0:
return False
return True
def prime(number):
for i in range(2,number,1):
if number % i == 0:
return False
return True
entry = int(input("Please enter the number: "))
while True:
if prime(entry):
print ("It's a prime number. ")
continue
else:
print ("It's not a prime number.. ")
continue
You will entry a number then this function will give you if its a prime or not. Check the function it will solve your problem.
ALSO You can upgrade the speed of your program. You know prime numbers can not be even, so you you dont have to check even numbers
like 4-6-8-26. So in the range function, which is (2,number) add "2"
end of it. like (3,number,2) then program will not check even numbers.
ALSO a factor can not be bigger than that numbers square root. So you dont have to check all of numbers till your main number, its
enough to check your numbers square root. like: (2,number**0.5) that
means from 2 to your number square root. So double up for program
speed.
So the function will be:
def prime(number):
for i in range(3,(number**0.5)+1),2):
if number % i == 0:
return False
return True
The first function enough for you actually. I am working with huge numbers, so I have to upgrade the speed of my program.
def is_prime(x):
for n in range(2, x-1):
if n == 0:
return False
elif n == 1:
return False
elif n == 2:
return True
elif x % n == 0:
return False
else:
return True
What you are doing wrong is , the first three if elif blocks are executed every time in the loop. So, they should be outside the for loop. Also.
if x%n==0:
return True
It is fine. But the later
else:
return True
is wrong because whenever the first n does not divide the x, it will return Composite. So,
return True
block must be outside the for loop.
Other optimizations can be done by yourself.
This is how I solved it
def is_prime(n):
if n==1:
print("It's not a Prime number")
for z in range(2,int(n/2)):
if n%z==0:
print("It's not a Prime number")
break
else:
print("It's a prime number")
or if you want to return a boolean value
def is_prime(n):
if n==1:
return False
for z in range(2,int(n/2)):
if n%z==0:
return False
break
else:
return True
I apologize in advance if this is a duplicate question - my search for python and modulus ran up to 8 pages of questions and that combined with my relatively little coding experience made it somewhat difficult for me to check thoroughly to see if there was anything extremely similar out there.
While trying to solve a Project Euler question, I wrote a function for testing whether or not a number was a prime number:
import math
def isprime(n):
if n % 1 != 0:
return(False)
else:
for j in range(2, math.ceil(math.sqrt(n)) + 1):
if n % j == 0:
return(False)
else:
return(True)
break
This works pretty well with small numbers, but with very large numbers that definitely aren't prime (e.g. I put in isprime(1012321312412431434334545555) and the function gives me a value of True). Why is this the case?
EDIT: as pointed out by roippi and confirmed by my further investigations, this function actually does not work for a lot of smaller odd composite numbers. I'm trying to figure out why that doesn't work for now.
I believe your problem is that the return is in the wrong place. Your code currently only loops through the 2, and any odd number is obviously not divisible by 2. So, it goes into the if n%j==0, returns True, and since a return breaks out of the loop, stops going. So, any odd number will return True.
Instead, try:
def isprime(n):
if n % 1 != 0:
return True
else:
for j in range(2, math.ceil(math.sqrt(n))):
if n % j != 0:
return False
return True
I think that works.
EDIT: No, it actually doesn't. Here, I'll post a different prime checker:
def isprime(n):
'''check if integer n is a prime'''
n = abs(int(n))
if n < 2:
return False
if n == 2:
return True
if not n & 1:
return False
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True
First of all, n % 1 == 0 will always return true for integers, because this tests if n is divisible by 1. So this is a bit of a nonsical test. If you want to check for odd/even numbers, use n % 2.
It does check for decimals, but in that case I think it's better to throw an error.
A better algorithm to test for prime is something like this:
def isPrime(n):
if n < 2:
return False
if n < 4:
return True
for x in range(2,ceil(sqrt(n)) + 1):
if (n % x == 0):
return False
return True