Function displays nothing after returning - python

import math
def erathosthene(n):
for d in range(2, int(math.sqrt(n) + 0.5)):
while n % d != 0:
d =+ 1
if n % d == 0:
print('this number isn\'t prime')
return False
else:
print('this number is prime')
return True
erathosthene(35)
it literally display nothing and honestly idk why it display nothing
there's nothing after return in terminal

What you're doing is a primality test and the problems of your code are
let the for loop increase d, don't increase it by yourself too
if n is divisible by d then you end as it is not prime
if n is NOT divisible by the current d, that doesn't mean it is prime, you wait to wait
loop until sqrt(x)+1 not sqrt(x)+0.5, because for
add condition for numbers < 2
def erathosthene(n):
if n < 2:
return False
for d in range(2, int(math.sqrt(n) + 1)):
if n % d == 0:
return False
return True
Then call with a print so your code displays something
print(erathosthene(6))
For better implementation, you can see isPrime Function for Python Language for example

Related

I'm trying to print the integers from 0 to 100 and identify the prime numbers

I've worked a lot on this but I can't figure out the problem. Can you help me?
The code should print numbers from 0 to 100 and print next to the prime numbers "Prime". The first function works but if I try to print the numbers all togheter the "prime" tag gets misplaced.
def testPrime(numTest):
if numTest <= 1:
return False
if numTest == 2:
return True
for i in range(2, numTest):
if (numTest % i) == 0:
return False
else:
return True
def printPrimes (lenght):
i = 0
while i <= lenght:
if testPrime(i):
print(str(i) + "Prime")
else:
print(str(i))
i += 1
printPrimes(100)
The logic in testPrime() is flawed. There are faster techniques but here's a trivial approach that may help:
def testPrime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5)+1, 2):
if n % i == 0:
return False
return True
Since a prime number is defined a number a natural number greater than 1 that is not a product of two smaller natural numbers
I think this is the only lines you need.
def testPrime(n):
for i in range(2,n):
if n%i == 0:
return False
return True

Almost Perfect Kattis (Time Limit Exceeded )

Hope you can help me in this problem :
So the problem is Almost Perfect in Kattis.
https://open.kattis.com/problems/almostperfect
This is my code. the first test is passed but the second no it gives me am message (Time Limit Exceeded)
def isperfect(n):
l=0
for i in range(1,n):
if n%i==0:
l+=i
if l>n+2 :
print(f"{n} not perfect")
break
if(l==n):
print(f"{n} perfect")
elif abs((n-l))<=2:
print(f"{n} almost perfect")
else :
print(f"{n} not perfect")
while True:
try :
n = int(input())
isperfect(n)
except EOFError:
break;
Where is the mistake ? or how can I optimise it ?
Thank you in advance
The issue is that the code is simply too slow. Luckily, there's a simple optimization that can save you.
Note that if d is a divisor of n, then n / d is also a divisor. Furthermore, if d is lesser than sqrt(n), then n / d is greater than sqrt(n) (and vice-versa).
What this effectively means is we only need to check numbers up to sqrt(n) instead of checking all the way to n. And for every divisor d we find, we also make sure to add n / d to the divisor sum, except when d is 1 or exactly sqrt(n).
Here's what that might look like in your code:
l = 1
for i in range(1, int(sqrt(n)) + 1):
if n % i == 0:
l += i
if i < sqrt(n): l += n // i
if l > n + 2: break
Another minor bug is that when l > n + 2 you'll print the message twice, which is easily solved by removing the print before break.
import sys
import math
def almostPerfect(num):
count = 1
for i in range (2,int(math.sqrt(num)) + 1):
if(num % i == 0):
count += i
if(i*i != num):
count += num // i
if(count == num):
return "{} perfect".format(num)
elif (count == (num-2)):
return "{} almost perfect".format(num)
elif (count == (num+2)):
return "{} almost perfect".format(num)
elif (count == (num-1)):
return "{} almost perfect".format(num)
elif (count == (num+1)):
return "{} almost perfect".format(num)
else:
return "{} not perfect".format(num)
for line in sys.stdin.readlines():
line = int(line)
print(almostPerfect(line))
This could be another solution that works for python, and I think we need to take note about (i*i != num), so that we don't start adding the same number.

When the variable goes up, the next time the loop runs it doesn't use the new variable number

My code is supposed to find the first 100 of the p1*p2...*pn+1 sequence and then test if they are prime.
primes = [2,3]
def isItPrime(n):
tests = primes.copy()
while len(tests) != 0:
if n % tests[-1] == 0:
return False
elif n % tests[-1] != 0:
tests.pop()
if len(tests) == 0:
primes.append(n)
return True
def firstNPrimes(n) :
a = 4
while len(primes) < n :
isItPrime(a)
a += 1
print(primes)
def multiplyList(q) :
result = 1
for x in q:
result = result * x
return result
h = 1
while h < 100 :
w = 2
firstNPrimes(w)
result = multiplyList(primes)
float(result)
result += 1
print(result)
w += 1
print(w)
h += 1
I don't get any errors but my code doesn't work. I think w either doesn't go up or it goes up and the program doesn't use it. When I print w after I make it go up, it goes up but the next time the program runs it doesn't use the new number.
If I understood the task, it is required to generated prime according to the Euclid's proof of Euclid's theorem from all primes between 2 and N and then print all generated primes for intervals where N goes from 2 to 100. I assume 100 is included, though it's not important.
Let's define a function is_prime(n) which return True or False. To check weather a number is prime you can check that the number is not divisible by any number from 2 to square root of the number. You might ask why square root? Because if A*B = N and if A is smaller than square root of N then B will be bigger then square root of N and we don't need to check B if we have already checked A. Let's use ceil(sqrt(N)) which returns the smallest integer value that is bigger than or equal to a number.
get_prime_range(n) generates all primes from 2 to n where n is included
generate_prime(primes) computes prime_1*prime_2* ... *prime_k + 1 which is also a prime number.
from math import sqrt, ceil
def is_prime(n):
for i in range(2, math.ceil(math.sqrt(n))):
if n % i == 0:
return False
return True
def get_prime_range(n):
primes = []
for i in range(2, n+1):
if is_prime(i):
primes.append(i)
return primes
def generate_prime(primes):
new_prime = 1 if primes else None
for prime in primes:
new_prime *= prime
return new_prime + 1
for n in range(2, 101):
print(generate_prime(get_prime_range(n)))
After tinkering with & adjusting your code, I think the following works:
def isItPrime(n):
tests = primes.copy()
while len(tests) != 0:
if n % tests[-1] == 0:
return False
elif n % tests[-1] != 0:
tests.pop()
if len(tests) == 0:
primes.append(n)
return True
def firstNPrimes(n, a=5) :
while len(primes) < n :
isItPrime(a)
a += 1
def multiplyList(q, result=1):
for x in q:
result *= x
return result
primes = [2,3]
w, h, n_iter = 2, 1, 100
while h < n_iter :
print("{}/{}".format(h,n_iter)) # To see progress
firstNPrimes(w)
result = multiplyList(primes)
float(result)
result += 1
w += 1
h += 1
print("Primes: {}".format(primes))
print("Product of the primes: {}".format(result))
Let me know if this is not what you expect.

determining if random Int is prime or not

I have a little problem when i need to determine if a number , x is a prime number or not.
x will be a randomly generated positive integer and i get the following message when i execute code:
Your function fails on is_prime(2). It returns None when it should return True.
My code:
def is_prime(x):
if x < 2:
return False
else:
for n in range(2, x):
while x % n == 0:
return False
break
else:
return True
i want the while loop to iterate through n == 2 up to n == (x-1) but it doesnt seem to do it!
what am i doing wrong?
You could write this function much more simplier:
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
So your call for is_prime(2) wouldn't pass the if test and wouldn't be used in the for run and would just return True.
All other prime numbers should be tested if they are greater than 3 and not even.

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