Python primes function giving incorrect output - python

I have been asked to create two functions, the first is_divisible(n,primes) to check if a number is divisible by any other numbers in prime
and then the second which would use the first to find all the prime numbers in a particular range.
I don't know why, but i cannot work out how to get the primes to show. Anything obvious about what I am doing wrong?
def is_divisible(n, primes):
for p in primes:
if n % p == 0:
return True
else:
return False
def find_primes(N):
primes=[]
for n in range(2, N+1):
is_divisible(n,primes)
if False:
primes.append(n)
print(primes)
find_primes(20)

def is_divisible(n, primes):
for p in primes:
if n % p == 0:
return True
return False # Only return False if no matches
def find_primes(N):
primes=[]
for n in range(2, N+1):
if not is_divisible(n,primes)
primes.append(n)
print(primes)
print find_primes(20)

This if statement will never be true:
if False:
primes.append(n)
Rewrite the code like this:
if is_divisible(n,primes)==False:
primes.append(n)

This code is wrong:
is_divisible(n,primes)
if False:
primes.append(n)
You should check if the divisibility inside the if condition. Try this:
if not is_divisible(n,primes):
primes.append(n)
Python evaluates 0 to False, and all numbers otherwise.
So, it's not necessary to do something like "if condition == True". Use just if condition.

Related

Python - for-loop does not enter correct argument for boolean parameter

I am trying to generate a for-loop in Python that should classify any number as prime/not prime. The suggested command is:
def prime_checker(number):
is_prime = True
for n in range(2, number):
if number % n == 0:
is_prime = False
if is_prime == True:
print("It is a prime number.")
else:
print("It is not a prime number.")
The suggested command above works well. However, I would like to generate the parameter as is_prime = bool() (i.e. with no standard value), and only after that the function will classify is_prime as either "True" or "False". The reason is that I do not like the idea of generating variables with standard arguments; instead I prefer to first generate variables populated with missing values, and only then to have them filled in with the proper argument. I tried this command, but it will output only "It is a prime number.":
def prime_checker(number):
is_prime = bool()
for n in range(2, number):
if number % n == 0:
is_prime = False
else:
is_prime = True
if is_prime == True:
print("It is a prime number.")
else:
print("It is not a prime number.")
I wonder if anybody knows why the command above will output only "It is a prime number."
I'm not sure why you don't like this idea, it is pretty standard in python (and in programmation in general) and often used. Anyway, the closest thing you could write would be:
is_prime = None
which is the equivelent in python to declaring a variable without assigning a value.
My final command would be:
def prime_checker(number):
is_prime = None
if number <2:
is_prime = False
print(f"{number} is not prime")
else:
for n in range(2,number):
if number % n == 0:
is_prime = False
if is_prime == False:
print(f"{number} is not prime")
else:
is_prime = True
print(f"{number} is prime")
Thank you for all who commented in this post! Any other comments are of course welcome.
It's because your second function does
else:
is_prime = True
within the for-loop.
So if it discovers that it's not a prime number for one value of n, the next iteration(n+1) might make it so is_prime equal to True.
For example, if you're testing the number 4:
It's divisible by 2, so set is_prime to False
It's not divisible by 3, so set is_prime to True
You need to add a break after you discover it's not prime, so that it won't try and keep checking other numbers.
And doing is_prime = bool() sets it to False, anyway.
Finally, just an add-on, there are faster ways to check for primality:
import math
def is_prime(number):
if number <= 2:
print(number, "is prime!")
return True
for i in range(3, math.floor(math.sqrt(number))+1, 2):
if number%i == 0:
print(number, "is prime!")
return True
print(number, "is not prime!")
return False

Writing a function that checks prime numbers

def primecheck(num):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
return False
break
else:
return True
Im trying to make a function that checks if an input is prime or not. This code does return True if I enter a prime number, but it also enters true whenever I enter a multiple of a prime number? Why is this happening
thanks
The problem with your code is that you have return statements in the first iteration of the loop. Also break statement is not needed. Moving return True outside the loop gives the solution:
def primecheck(num):
for i in range(2, num):
if num % i == 0:
return False
return True
I leave num = 0 or 1 for you.
Or you can simply use for else for this.
def primecheck(num):
if num>1:
for i in range(2, num):
if num%i==0:
return False
break
else:
return True
print(primecheck(15))
The problem is with your else statement, no need for it. And also break is not needed
def primecheck(num):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
return False
return True
or you can solve it without any iterations. You can use Fermat's little theorem to solve this easily(hope you refer it),
def primeChecker(n):
m = 2 #can be any number
if(n > 1):
if (((m**n)-m)%n == 0): #Using Fermat's little theorem
return True
return False
n = int(input());
if primeChecker(n):
print('{} - is prime number'.format(n))
else:
print('{} - NOT a prime number'.format(n))
Doing a little research on the internet will help to solve these types of questions much easier and efficiently. ;). Cheers!
You are using return in the else part. So your code will break after 1st iteration and print the result of first iteration.
You can do something like this:
def primecheck(num):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
return False
return True
print(primecheck(15))

My For loop won't iterate through a list

I have to determine if all the numbers in a list are prime numbers and then return a boolean "True" or "False" statement depending on the outcome. I made some conditional statements inside of a for loop to see if the number was prime or not.
Here's the code:
def all_primes(xs):
is_prime = None
for i in xs:
if i < 2:
is_prime = False
return is_prime
break
elif (i % 2 == 0) and (i % i == 1):
is_prime = False
return is_prime
break
else:
is_prime = True
return is_prime
The problem is, and I saw this in the Python Visualizer, the for loop stops iterating after checking the first value in the list. I don't understand why as the syntax is the same as for loops I've used in the past.
I plugged in some example values like: all_primes([5,2,11,37]) or all_primes([5,2,4,37]) and the return value is always true since 5 is the first number on the list and the only number that is being iterated.
Any ideas as to why?
You have a return and a break in your if/else block, you should get rid of them. Also the return in the else should be outside, or it will just return whenever he finds a "prime".
def all_primes(xs):
is_prime = None
for i in xs:
if i < 2:
is_prime = False
return is_prime
elif (i % 2 == 0):
is_prime = False
return is_prime
else:
is_prime = True
return is_prime
After this, you should know, that you are not really checking primes.
Here is not the most efficient way but its clear how to:
def all_primes(xs):
def checkPrime(n):
if n < 2:
return False
for i in xrange(2, n):
if n%i == 0:
return False
return True
return all(map(checkPrime, xs))
EDIT:
without the map functions, you just have to iterate with a for loop:
def all_primes(xs):
def checkPrime(n):
if n < 2:
return False
for i in xrange(2, n):
if n%i == 0:
return False
return True
for n in xs:
if not checkPrime(n):
return False
return True
You should see the problem the other way around.
If you you find a number which is not prime you should return False, and after your loop end you should return True.

Trying to find the prime numbers using Python

Below is my code to find the prime number using Python which is not working. Here the function prime will take an integer as input and return whether its a prime number or not. Could you please sort out the problem and explain it.
def prime(x):
if x == 0 or 1:
return False
elif x == 2:
return True
else:
for n in range(2, x):
if x % n == 0:
return False
else:
return True
I think i have sorted out the first issue, the first "if" statement should be if x == 0 or x == 1. Now what about the rest.
What does your for loop?
if x % n == 0:
return False
else:
return True
which by the way eqals return bool(x % n)
So, you return in first iteration, when n == 2.
The whole for loop equals return bool(x % 2), which simply checks if x is diviseable by 2.
That's not what you want.
So, what do you want?
You want to check if x is not diviseable by any numer from range(2, x).
You know that x is not prime, if you find one n from range(2, x), for which x % n == 0 is True.
You know that x is prime, when there is no n in range(2, x), for which x % n == 0 is True.
When can you say that none of n from range is a divisor of x?
After checking all ns from range!
After is the key here.
After the loop, in which you try to find divisor, you can only tell that x is prime.
I hope you now understand the code others posted without explanation.
Note: alternative syntax
Code others posted is correct. However, in Python there is second way writing the for, using for .. else:
for x in range(2, x):
if x % n == 0:
return False
else:
return True
The problem is that the return true should not happen until the for loop has completed.
what we have in the original code is a cuple of tests for trivial cases (x less than 3)
and then a loop for testing all the larger numbers.
In the loop an attempt is made to divide x by a smaller number (starting with 2) and then if it divides evenly False is returned, if it does not True is returned, that is the mistake, instead of returning true, the loop should be allowed to repeat, and division should be tried again with the next number, and only after the supply of divisors (from the for loop) has been exhausted should true be returned.
here's a fixed version:
def prime(x):
if x <= 1:
return False
elif x == 2:
return True
else:
for n in range(2, x):
if x % n == 0:
return False
return True
Others have commented that the loop need not continue all the way up to x and that stopping at sqrt(x) is sufficient, they are correct. doing that will make it faster in almost all cases.
Another speed up can be had if you have a list of small primes (upto sqrt(x)) - you need only test divisibility by the primes below sqrt(x),and not every integer in that range.
The below code is for finding the prime number from 2 to nth number.
For an example, the below code will print the prime number from 2 to 50 and also it will print the number in between 2 to 5o which is not prime.
import time
i=2
j=2
count=0
while(i<50):
while (i>j):
if (i%j)==0:
count=count+1
j=j+1
else:
j=j+1
if count==0:
print i," is a prime"
else:
print i," is not a prime"
i=i+1
j=2
count=0
time.sleep(2)

Prime number check acts strange [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 7 years ago.
I have been trying to write a program that will take an imputed number, and check and see if it is a prime number. The code that I have made so far works perfectly if the number is in fact a prime number. If the number is not a prime number it acts strange. I was wondering if anyone could tell me what the issue is with the code.
a=2
num=13
while num > a :
if num%a==0 & a!=num:
print('not prime')
a=a+1
else:
print('prime')
a=(num)+1
The result given when 24 is imputed is:
not prime
not prime
not prime
prime
How would I fix the error with the reporting prime on every odd and not prime for every even?
You need to stop iterating once you know a number isn't prime. Add a break once you find prime to exit the while loop.
Making only minimal changes to your code to make it work:
a=2
num=13
while num > a :
if num%a==0 & a!=num:
print('not prime')
break
i += 1
else: # loop not exited via break
print('prime')
Your algorithm is equivalent to:
for a in range(a, num):
if a % num == 0:
print('not prime')
break
else: # loop not exited via break
print('prime')
If you throw it into a function you can dispense with break and for-else:
def is_prime(n):
for i in range(3, n):
if n % i == 0:
return False
return True
Even if you are going to brute-force for prime like this you only need to iterate up to the square root of n. Also, you can skip testing the even numbers after two.
With these suggestions:
import math
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
Note that this code does not properly handle 0, 1, and negative numbers.
We make this simpler by using all with a generator expression to replace the for-loop.
import math
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
def isprime(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up
# the square root of n for all odd numbers
for x in range(3, int(n**0.5) + 1, 2):
if n % x == 0:
return False
return True
Taken from:
http://www.daniweb.com/software-development/python/code/216880/check-if-a-number-is-a-prime-number-python
def is_prime(n):
return all(n%j for j in xrange(2, int(n**0.5)+1)) and n>1
The two main problems with your code are:
After designating a number not prime, you continue to check the rest of the divisors even though you already know it is not prime, which can lead to it printing "prime" after printing "not prime". Hint: use the `break' statement.
You designate a number prime before you have checked all the divisors you need to check, because you are printing "prime" inside the loop. So you get "prime" multiple times, once for each divisor that doesn't go evenly into the number being tested. Hint: use an else clause with the loop to print "prime" only if the loop exits without breaking.
A couple pretty significant inefficiencies:
You should keep track of the numbers you have already found that are prime and only divide by those. Why divide by 4 when you have already divided by 2? If a number is divisible by 4 it is also divisible by 2, so you would have already caught it and there is no need to divide by 4.
You need only to test up to the square root of the number being tested because any factor larger than that would need to be multiplied with a number smaller than that, and that would already have been tested by the time you get to the larger one.
This example is use reduce(), but slow it:
def makepnl(pnl, n):
for p in pnl:
if n % p == 0:
return pnl
pnl.append(n)
return pnl
def isprime(n):
return True if n == reduce(makepnl, range(3, n + 1, 2), [2])[-1] else False
for i in range(20):
print i, isprime(i)
It use Sieve Of Atkin, faster than above:
def atkin(limit):
if limit > 2:
yield 2
if limit > 3:
yield 3
import math
is_prime = [False] * (limit + 1)
for x in range(1,int(math.sqrt(limit))+1):
for y in range(1,int(math.sqrt(limit))+1):
n = 4*x**2 + y**2
if n<=limit and (n%12==1 or n%12==5):
# print "1st if"
is_prime[n] = not is_prime[n]
n = 3*x**2+y**2
if n<= limit and n%12==7:
# print "Second if"
is_prime[n] = not is_prime[n]
n = 3*x**2 - y**2
if x>y and n<=limit and n%12==11:
# print "third if"
is_prime[n] = not is_prime[n]
for n in range(5,int(math.sqrt(limit))):
if is_prime[n]:
for k in range(n**2,limit+1,n**2):
is_prime[k] = False
for n in range(5,limit):
if is_prime[n]: yield n
def isprime(n):
r = list(atkin(n+1))
if not r: return False
return True if n == r[-1] else False
for i in range(20):
print i, isprime(i)
Your problem is that the loop continues to run even thought you've "made up your mind" already. You should add the line break after a=a+1
After you determine that a number is composite (not prime), your work is done. You can exit the loop with break.
while num > a :
if num%a==0 & a!=num:
print('not prime')
break # not going to update a, going to quit instead
else:
print('prime')
a=(num)+1
Also, you might try and become more familiar with some constructs in Python. Your loop can be shortened to a one-liner that still reads well in my opinion.
any(num % a == 0 for a in range(2, num))
Begginer here, so please let me know if I am way of, but I'd do it like this:
def prime(n):
count = 0
for i in range(1, (n+1)):
if n % i == 0:
count += 1
if count > 2:
print "Not a prime"
else:
print "A prime"
This would do the job:
number=int(raw_input("Enter a number to see if its prime:"))
if number <= 1:
print "number is not prime"
else:
a=2
check = True
while a != number:
if number%a == 0:
print "Number is not prime"
check = False
break
a+=1
if check == True:
print "Number is prime"
a=input("Enter number:")
def isprime():
total=0
factors=(1,a)# The only factors of a number
pfactors=range(1,a+1) #considering all possible factors
if a==1 or a==0:# One and Zero are not prime numbers
print "%d is NOT prime"%a
elif a==2: # Two is the only even prime number
print "%d is prime"%a
elif a%2==0:#Any even number is not prime except two
print "%d is NOT prime"%a
else:#a number is prime if its multiples are 1 and itself
#The sum of the number that return zero moduli should be equal to the "only" factors
for number in pfactors:
if (a%number)==0:
total+=number
if total!=sum(factors):
print "%d is NOT prime"%a
else:
print "%d is prime"%a
isprime()
This is a slight variation in that it keeps track of the factors.
def prime(a):
list=[]
x=2
b=True
while x<a:
if a%x==0:
b=False
list.append(x)
x+=1
if b==False:
print "Not Prime"
print list
else:
print "Prime"
max=int(input("Find primes upto what numbers?"))
primeList=[]
for x in range(2,max+1):
isPrime=True
for y in range(2,int(x**0.5)+1) :
if x%y==0:
isPrime=False
break
if isPrime:
primeList.append(x)
print(primeList)
Prime number check.
def is_prime(x):
if x < 2:
return False
else:
if x == 2:
return True
else:
for i in range(2, x):
if x % i == 0:
return False
return True
x = int(raw_input("enter a prime number"))
print is_prime(x)
# is digit prime? we will see (Coder: Chikak)
def is_prime(x):
flag = False
if x < 2:
return False
else:
for count in range(2, x):
if x % count == 0:
flag = True
break
if flag == True:
return False
return True

Categories