Find the next prime number in Python - 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

Related

To find a prime palindrome number

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

Next Prime Number in Python

I'm a beginner in Python and I'm practicing to code this problem I saw. Next prime is needed, but there are limitations on the input. I have searched for similar questions, but my code is still not working. Hope you can help. Thank you!
The problem I get is when I enter 32, the results show 33 when the next prime is 37...
Here's my code so far.
num = int(input("Enter a positive number:"))
import math
def nextprime(n):
if n < 0:
raise ValueError
for next in range(n + 1, n +200):
if next > 1:
for i in range(2, next):
if (next % i) == 0:
break
else:
return next
In your code when you arrive to a number that reminder is not zero you return that number. You need a flag for every number this flag is True if can be divide flag convert to False for the first number that flag not convert to false return that number like below.
Don't use next because this is a builtin function.
Try this: (I don't improve your code)
def nextprime(n):
if n < 0:
raise ValueError
for i in range(n + 1, n +200):
if i > 1:
pr = True
for j in range(2, i):
if (i % j) == 0:
pr = False
break
if pr:
return i
return 'not found'
You can also try this code, write function to check that a number is prime or not like def is_prime then for number of larger that you input num find min number next. (this answer from this thread.)
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(32))
You can also use sympy like below: (this answer from this thread.)
from sympy import *
nextprime(32)
def next_prime(n):
while True:
n=n+1
for i in range (2,int(n/2)):
if n%i==0:
break
else:
return n
print(next_prime(67))
Few off-topic tips:
as user1740577 mentioned, don't use next as a variable name
refrain from using eval when possible, it's okay here, but in real project this will lead to big no-no.
Place imports at the very top of your script
Consider using variable names i and j only for iterations.
For duplicate except blocks use (Error, Error)
As for solution to your problem, with some adjustments, if you don't mind
def next_prime(n: int) -> int:
if n < 0:
raise ValueError('Negative numbers can not be primes')
# Base case
if n <= 1:
return 2
# For i as every odd number between n + 1 and n + 200
for i in range(n + 1 + (n % 2), n + 200, 2):
# For every odd number from 3 to i (3 because we covered base case)
for j in range(3, i, 2):
# If remained is equals to 0
if not i % j:
# break current loop
break
# If loop j didn't break [nobreak: ]
else:
return i
raise RuntimeError('Failed to compute next prime number :c')
def main():
while True:
try:
num = int(input('Enter positive number: '))
print(f'Next prime is: {next_prime(num)}')
break
except ValueError:
print('Please enter a positive integer!')
if __name__ == '__main__':
main()
Made some speed improvements to the code from #rajendra-kumbar:
#!/usr/bin/env python
import sys
import time
import math
def next_prime(number):
if number < 0:
raise ValueError('Negative numbers can not be primes')
# Base case
if number <= 1:
return 2
# if even go back 1
if number % 2 == 0:
number -= 1
while True:
# only odds
number += 2
#only need to check up to and including the sqrt
max_check = int(math.sqrt(number))+2
# don't need to check even numbers
for divider in range(3, max_check, 2):
# if 'divider' divides 'number', then 'number' is not prime
if number % divider == 0:
break
# if the for loop didn't break, then 'number' is prime
else:
return number
if __name__ == '__main__':
number = int(sys.argv[1].strip())
t0 = time.time()
print('{0:d} is the next prime from {1:d}'.format(next_prime(number), number))
run_time = time.time() - t0
print('run_time = {0:.8f}'.format(run_time))
it is about twice as fast
You can try something like simple:
def is_prime(number:int):
check = 0
for i in range(2,number):
if number % i == 0:
check += 1
if check == 0:
return True
else:
return False
def next_prime(value):
check = value + 1
while is_prime(check) is False:
check += 1
return check
value = int(input("Insert the number: "))
print(next_prime(value))

Check if a number can be divided into prime partitions

Can somebody solve this problem on Python ?
A positive integer m can be partitioned as primes if it can be written as p + q where p > 0, q > 0 and both p and q are prime numbers.
Write a Python function that takes an integer m as input and returns True if m can be partitioned as primes and False otherwise.
Tried this, but does not work for all testcases, for example it should return True for 3432, it returns False.
def partition(num):
primelist=[]
for i in range(2,num + 1):
for p in range(2,i):
if (i % p) == 0:
break
else:
primelist.append(i)
for x in primelist:
y= num-x
for z in range(2,y):
if y%z == 0:
return False
return True
The error lies in the second for loop. You are looping through possible primes x, and wish to then check that y = num - x is also prime.
The error in your logic is that in the second for loop, if the first element in the loop y = num - x is not prime, it will return False, without checking any of the other possible values.
You could correct this by moving the return False statement out one loop, but since you have already generated a list of primes less than num, primelist (and since y = num - x, (if prime y exists) it will be in this list), you can just check for membership of the list:
for x in primelist:
y= num-x
# Note: num = x + y, thus need only check y prime
if y in primelist:
return True
# If no such y is prime, not possible
else:
return False
Note: I would advise making the logic of your script more modular, separating out the prime list generator into its own function:
def partition(num):
"""
Return True if there exist primes x,y such that num = x + y.
Else return False.
"""
primelist = primes(num)
for x in primelist:
y= num-x
# Note: num = x + y, thus need only check y prime
if y in primelist:
return True
# If no such y is prime, not possible
else:
return False
def primes(num):
"""Return list of all primes less than num."""
primelist=[]
for i in range(2,num + 1):
for p in range(2,i):
if (i % p) == 0:
break
else:
primelist.append(i)
return primelist
final solution i got:
def primepartition(m):
primelist=[]
if m<0:
return False
else:
for i in range(2,m + 1):
for p in range(2,i):
if (i % p) == 0:
break
else:
primelist.append(i)
for x in primelist:
y= m-x
if y in primelist:
return True
return False
The given below code can hopefully give you the correct output.
def factors(n):
factorslist = []
for i in range(1, n+1, 1):
if n % i == 0:
factorslist.append(i)
return(factorslist)
def prime(n):
if factors(n) == [1, n] and n > 1:
return(True)
def primelist(n):
primenolist = []
for i in range(1, n+1, 1):
if prime(i) == True:
primenolist.append(i)
return(primenolist)
def primepartition(m):
if m > 0:
primenolist = primelist(m)
checklist = []
for p in primenolist:
q = m - p
if q in primenolist and p > 0 and q > 0:
checklist.append((p,q))
if len(checklist) > 0:
return(True)
else:
return(False)
else:
return(False)
Another approach,
Initially, we store all prime elements upto m and check for pair of primes whose sum equal to m
def primepartition(a):
l=[2]#since 'a' should be >=2 for below loops, we took here 2(1st prime).
for i in range(2,a):
flag=0
for j in range(2,i):
if i%j==0:
flag=0
break
else:
flag=1
if flag==1:
l.append(i)
for i in l:
for j in l:
if i+j==a:
return True
return False
n=int(input("Enter any number: "))
list=[]
for num in range(0,n + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
list.append(num)
if (n<= 1):
print("False")
#print("It is not positive ")
else:
for i in list:
y = num -i
if (y in list):
print("True")
#print(y,"+",i,"=",n)
#print(i,"+",y,"=",n)
#print("The number can be expressed as the sum of two prime numbers.")
break
else:
print("False")
#print("The number can not be expressed as the sum of two prime numbers.")
Slight Variation of your code:
def primepartition0(m):
primelist=[]
if m<0:
return False
else:
for i in range(2,m + 1):
for p in range(2,i):
if (i % p) == 0:
break
else:
primelist.append(i)
for x in primelist:
for y in primelist:
if x != y and x+y == m:
return True
return False
An alternate approach that attemps to reduce the amount of code necessary:
def primepartition(m):
if m > 3:
for number in range(m // 2, m - 1):
difference = m - number
for psuedoprime in range(2, int(number ** 0.5) + 1):
if number % psuedoprime == 0 or difference > psuedoprime and difference % psuedoprime == 0:
break
else: # no break
return number, difference # as good a non-False result as any other...
return False
def factors(n):
factlist = []
for i in range(1,n+1):
# Since factors of 2 cannot be primes, we ignore them.
if n%i==0 and i%2!=0:
factlist.append(i)
return factlist
def isprime(n):
return(factors(n)==[1,n])
def preimesupto(n):
primelist = []
if n>=2:
primelist.append(2)
for i in range(n):
if isprime(i):
primelist.append(i)
return primelist
def primepartition(n):
if n<0:
return False
primelist = preimesupto(n)
for i in primelist:
j = n-i
if j in primelist:
return True
else:
return False
If you're not required to produce the actual primes but only test if there exists a pair of primes p and q such that p+q == N, you could make this very simple based on the Goldbach conjecture. All even numbers can be expressed as the sum of two primes. So return True if the number is even and check if N-2 is prime for odd numbers (because 2 is the only even prime and that's the only prime that will produce another odd number when starting from an odd number). This will boil down to a single prime test of N-2 only for odd numbers.
def primePart(N):
return N%2==0 or all((N-2)%p for p in range(3,int(N**0.5)+1,2))
primePart(3432) # True
primePart(37+2) # True
primePart(13+41) # True
primePart(123) # False
If you want to actually find a pair of primes that add up to N, you can generate primes up to N and return the first prime >= N/2 where N - prime is one of the primes already found:
def findPQ(N):
if not primePart(N): return
if N%2: return 2,N-2
isPrime = [0]+[1]*N
for p in range(3,N,2):
if not isPrime[p]: continue
if 2*p>=N and isPrime[N-p]: return p,N-p
isPrime[p*p::p] = [0]*len(isPrime[p*p::p])
output:
findPQ(3432) # (1723, 1709)
findPQ(12345678) # (6172879, 6172799)
To go beyond 10^9 you will need a more memory efficient algorithm than the sieve of Eratosthenes that is just as fast. This can be achieved with a dictionary of multiples of primes to skip:
def findPQ(N):
if not primePart(N): return
if N%2: return 2,N-2
skip,primes = {},{2}
for p in range(3,N,2):
if p in skip:
prime = skip.pop(p)
mult = p + 2*prime
while mult in skip: mult += 2*prime
if mult <= N: skip[mult] = prime
else:
if 2*p>=N and N-p in primes: return p,N-p
if p*p<=N: skip[p*p]=p
if 2*p<=N: primes.add(p)
output (takes a while but doesn't bust memory space):
findPQ(1234567890) # (617283983, 617283907)
def checkprime(number):
fact=1
for r in range(2,number):
if number%r==0:
fact=fact+1
return(fact<2)
def primepartition(m):
for i in range(2,m):
flag=0
if checkprime(i) and checkprime(m-i)==True:
flag=1
break
return(flag==1)
def matched(s):
list_of_string=list(s)
for y in range(len(list_of_string)):
if list_of_string[y]=='(':
for z in range(y,len(list_of_string)):
if list_of_string[z]==')':
list_of_string[y]='#'
list_of_string[z]='#'
break
return('('not in list_of_string and ')'not in list_of_string)
def rotatelist(l,k):
if k>len(l):
k=int(k%len(l))
return(l[k:]+l[0:k])

Project Euler #3 with Python (Followup)

I'm working on problem #3 on project euler, and I've run into a problem. It seems that the program is copying all the items from factors into prime_factors, instead of just the prime numbers. I assume this is because my is_prime function is not working properly. How can I make the function do what I want? Also, in the code, there is a line that I commented out. Do I need that line, or is it unnecessary? Finally, is the code as a whole sound (other than is_prime), or is it faulty?
The project euler question is: The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?
A link to a previous question of mine on the same topic: https://stackoverflow.com/questions/24462105/project-euler-3-python?noredirect=1#comment37857323_24462105
thanks
import math
factors = []
prime_factors = []
def is_prime (x):
counter = 0
if x == 1:
return False
elif x == 2:
return True
for item in range (2, int(x)):
if int(x) % item == 0:
return False
else:
return True
number = int(input("Enter a number: "))
start = int(math.sqrt(number))
for item in range(2, start + 1):
if number % item == 0:
factors.append(item)
#factors.append(number/item) do i need this line?
for item in factors:
if is_prime(item) == True:
prime_factors.append(item)
print(prime_factors)
Yes, you need the commented line.
(It seems that on that case it's not necessary, but with other numbers the part of your code for getting factors would go wrong).
Check these references:
Prime numbers
Integer factorization
Why do we check up to the square root of a prime number to determine if it is prime or not
I got a very fast result on my computer with the following code:
#!/usr/bin/env python
import math
def square_root_as_int(x):
return int(math.sqrt(x))
def is_prime(number):
if number == 1:
return False
for x in range(2, square_root_as_int(number) + 1):
if x == number:
next
if number % x == 0:
return False
return True
def factors_of_(number):
factors = []
for x in range(2, square_root_as_int(number) + 1):
if number % x == 0:
factors.append(x)
factors.append(number/x)
return factors
factors = factors_of_(600851475143)
primes = []
for factor in factors:
if is_prime(factor):
primes.append(factor)
print max(primes)
# Bonus: "functional way"
print max(filter(lambda x: is_prime(x), factors_of_(600851475143)))
Your is_prime() returns early. Here's a fixed version:
def is_prime (x):
if x == 1:
return False
if x == 2:
return True
for item in range (2, int(x)):
if int(x) % item == 0:
return False
return True
you should not be using int(x) in the way that you currently are. i know you're forcing the int type because you want to convert from string input, but this will also allow the user to enter a float (decimal), and have it interpreted as either prime or not. that is bad behavior for the function. see my solution below. if you use eval to verify the input, you can just use x later, in place of int(x).
import math
factors = []
prime_factors = []
def is_prime (x):
x = eval(x) # this will cause a string like '5' to be evaluated as an integer.
# '5.2' will be evaluated as a float, on the other hand.
if type(x) != int:
raise Exception('Please enter an integer.') #prevents bad input
counter = 0 #this counter is not used. why is it initialized here?
if x == 1:
return False
elif x == 2:
return True
for item in range (2, x):
if x % item == 0:
return False
else:
return True
Use the while loop. n%i simply means n%i!=0
i = 2
n = 600851475143
while i*i <= n:
if n%i:
i+=1
else:
n //= i
print n

Python Beginner's Loop (Finding Primes)

I'm truly a beginner at python so I apologise for the lack of knowledge, but the reason I'm asking is that reading the Python manual and tutorial (http://docs.python.org/2.7/tutorial) I'm not unable to totally grasp how loops work. I've written some simple programs so I think I get the basics but for whatever reason this program that is meant to list all primes less than or equal to n is not working:
n = int(raw_input("What number should I go up to? "))
p = 2
while p <= n:
for i in range(2, p):
if p%i == 0:
p=p+1
print "%s" % p,
p=p+1
print "Done"
The output when I enter 100 for example is:
2 3 5 7 11 13 17 19 23 27 29 31 35 37 41 43 47 53 59 61 67 71 73 79 83 87 89 95 97 101 Done
Which looks almost right but for some reason contains 27, 35, 95, which are composite of course. I've been trying to pick apart the way my loop works but I just don't see where it skips checking for divisibility suddenly. I figured that if someone had a look they could explain to me what about the syntax is causing this. Thanks a bunch!
I would actually restructure the program to look like this:
for p in range(2, n+1):
for i in range(2, p):
if p % i == 0:
break
else:
print p,
print 'Done'
This is perhaps a more idiomatic solution (using a for loop instead of a while loop), and works perfectly.
The outer for loop iterates through all the numbers from 2 to n.
The inner one iterates to all numbers from 2 to p. If it reaches a number that divides evenly into p, then it breaks out of the inner loop.
The else block executes every time the for loop isn't broken out of (printing the prime numbers).
Then the program prints 'Done' after it finishes.
As a side note, you only need to iterate through 2 to the square root of p, since each factor has a pair. If you don't get a match there won't be any other factors after the square root, and the number will be prime.
Your code has two loops, one inside another. It should help you figure out the code if you replace the inner loop with a function. Then make sure the function is correct and can stand on its own (separate from the outer loop).
Here is my rewrite of your original code. This rewrite works perfectly.
def is_prime(n):
i = 2
while i < n:
if n%i == 0:
return False
i += 1
return True
n = int(raw_input("What number should I go up to? "))
p = 2
while p <= n:
if is_prime(p):
print p,
p=p+1
print "Done"
Note that is_prime() doesn't touch the loop index of the outer loop. It is a stand-alone pure function. Incrementing p inside the inner loop was the problem, and this decomposed version doesn't have the problem.
Now we can easily rewrite using for loops and I think the code gets improved:
def is_prime(n):
for i in range(2, n):
if n%i == 0:
return False
return True
n = int(raw_input("What number should I go up to? "))
for p in range(2, n+1):
if is_prime(p):
print p,
print "Done"
Note that in Python, range() never includes the upper bound that you pass in. So the inner loop, which checks for < n, we can simply call range(2, n) but for the outer loop, where we want <= n, we need to add one to n so that n will be included: range(2, n+1)
Python has some built-in stuff that is fun. You don't need to learn all these tricks right away, but here is another way you can write is_prime():
def is_prime(n):
return not any(n%i == 0 for i in range(2, n))
This works just like the for loop version of is_prime(). It sets i to values from range(2, n) and checks each one, and if a test ever fails it stops checking and returns. If it checks n against every number in the range and not any of them divide n evenly, then the number is prime.
Again, you don't need to learn all these tricks right away, but I think they are kind of fun when you do learn them.
This should work and is bit more optimized
import math
for i in range(2, 99):
is_prime = True
for j in range(2, int(math.sqrt(i)+1)):
if i % j == 0:
is_prime = False
if is_prime:
print(i)
Please compare your snippet with the one pasted below and you will notice where you were wrong.
n = int(raw_input("What number should I go up to? "))
p = 2
while p <= n:
is_prime=True
for i in range(2, p):
if p%i == 0:
is_prime=False
break;
if is_prime==True:
print "%d is a Prime Number\n" % p
p=p+1
you do not re-start the i loop after you find a non-prime
p = i = 2
while p <= n:
i = 2
while i < p:
if p%i == 0:
p += 1
i = 1
i += 1
print p,
p += 1
print "Done"
A while loop executes the body, and then checks if the condition at the top is True, if it is true, it does the body again. A for loop executes the body once for each item in the iterator.
def is_prime(n):
if n>=2:
for i in range(2, n):
if n%i == 0:
return False
return True
else:
return False
To find PRIME NUMBER
Let's do a couple more improvements.
You know 2 is the only even prime number, so you add 2 in your list and start from 3 incrementing your number to be checked by 2.
Once you are past the half-way point (see above sqrt and * examples), you don't need to test for a prime number.
If you use a list to keep track of the prime numbers, all you need to do is to divide by those prime numbers.
I wrote my code and each of the above items would improve my code execution time by about 500%.
prime_list=[2]
def is_prime(a_num):
for i in prime_list:
div, rem = divmod(a_num, i)
if rem == 0:
return False
elif div < i:
break;
prime_list.append(a_num)
return True
This in my opinion is a more optimised way. This finds all the prime numbers up to 1,000,000 in less than 8 seconds on my setup.
It is also one of my very first attempts at python, so I stand to be corrected
class prime:
def finder (self):
import math
n = long(raw_input("What number should I go up to? "))
for i in range(2, n):
is_prime = True
if i % 2 == 0:
is_prime = False
for j in range(3, long(math.sqrt(i) + 1), 2):
if i % j == 0:
is_prime = False
break
if is_prime:
print(i)
prime().finder()
print('Enter a Number: ')
number=abs(int(input()))
my_List=[0,1]
def is_prime(n):
if n in my_List:
return True
elif n>=2:
for i in range(2, n):
if n%i == 0:
return False
return True
else:
return False
if is_prime(number):
print("%d is Prime!"%number)
else:
print(number,'is not prime')
for i in range(2, p):
if p%i == 0:
p=p+1
print "%s" % p,
p=p+1
I am going to tell your error only,in line 3 you are incrimenting p but actually what you are missing is your i if your i in previous case is let say 13 then it will check your loop after 13 but it is leaving 2,3,5,7,11 so its an error .that is what happening in case of 27 your i before 27 is 13 and now it will check from 14.and I don't think u need an solution.
def findprime(num):
count = 0
for i in range(1,num+1):
list1 = []
for ch in range(1,i+1):
if i%1==0 and i%ch==0:
list1.append(ch)
if len(list1)==2:
count += 1
print(i,end=", ")
print()
return count
num2 = int(input("enter a number: "))
result=findprime(num2)
print("prime numbers between 1 and",num2,"are",result)
Here's a more extensive example with optimization in mind for Python 3.
import sys
inner_loop_iterations: int = 0
def is_prime(n):
a: int = 2
global inner_loop_iterations
if n == 1:
return("Not prime")
elif n == 2:
return("Prime")
while a * a <= n + 1:
inner_loop_iterations += 1
# This if statement reduces the number of inner loop iterations by roughy 50%
# just weeding out the even numbers.
if a % 2 == 0:
a += 1
else:
a += 2
if n % 2 == 0 or n % a == 0:
return ("Not prime")
else:
return ("Prime")
while True:
sys.stdout.write("Enter number to see if it's prime ('q' to quit): ")
n = input()
if not n:
continue
if n == 'q':
break
try:
n = int(n)
except ValueError:
print("Please enter a valid number")
if n < 1:
print("Please enter a valid number")
continue
sys.stdout.write("{}\n".format(is_prime(n)))
sys.stderr.write("Inner loops: {}\n\n".format(inner_loop_iterations))
inner_loop_iterations=0
This program has two main optimizations, first it only iterates from 2 to the square root of n and it only iterates through odd numbers. Using these optimizations I was able to find out that the number 1000000007 is prime in only 15811 loop iterations.
My fast implementation returning the first 25 primes:
#!/usr/bin/env python3
from math import sqrt
def _is_prime(_num: int = None):
if _num < 2:
return False
if _num > 3 and not (_num % 2 and _num % 3):
return False
return not any(_num % _ == 0 for _ in range(3, int(sqrt(_num) + 1), 2))
_cnt = 0
for _ in range(1, 1000):
if _is_prime(_):
_cnt += 1
print(f"Prime N°: {_:,} | Count: {_cnt:,}")
Better use
for i in range(2, p//2 + 1):

Categories

Resources