I recently started programming Python and was stuck at this particular Project Euler problem for finding the 1001st prime number.
My code:
L = [2]
def is_prime(x,L):
for el in L:
if x%el != 0:
flag = 1
else:
flag = 0
break
if flag == 1:
return True
elif flag == 0:
return False
a = 3
for k in range(1,1002):
if is_prime(a,L) is True:
L.append(a)
a += 1
k += 1
else:
a += 1
print(L)
print(len(L))
This prints the list of prime numbers upto 997 which is the 168th prime number. Can you tell me what am I doing wrong?
Your increment of k is pointless, because you're iterating a fixed range of numbers (k is replaced when the loop loops, the range can't be changed dynamically).
You want a while loop with a manually managed k:
a = 3
k = 1
while k < 1002:
if is_prime(a,L):
L.append(a)
a += 1
k += 1
else:
a += 1
Note: There may be some off-by-one logic errors here, but it expresses what I assume was your intent in the original code, fixing only the issue with managing k.
k += 1
That's where the problem is. Try this code:
for k in range(1, 1002):
print(k)
and then:
for k in range(1, 1002):
k += 1
print(k)
Your Mistake is that you are finding numbers that are prime UP to 1001 and Also variables of a loop cannot increase By the user
to fix that use a while loop
A Program To Find Up Prime's To Any Number would be:
import sys
def prime_num_finder():
i = 2
while True:
try:
p = int(input("Please enter up to what number the prime numbers should be: "))
break
except ValueError:
sys.stderr.write('ERROR\n')
sys.stderr.write(' Try again...\n')
while i != (p + 1):
x = i
if x % 2 and x % 3 and x % 5 and x % 7 > 0.1: # Checks if the remainder is greater than 0.1 to see if it has an remainder
r1 = True
else:
if i == 2 or i == 3 or i == 5 or i == 7:
r1 = True
else:
r1 = False
if r1 == True:
print(i, " is a prime number!")
else:
pass
i = i + 1
prime_num_finder()
quit()
That is a simple program to check if it is divisible by 2 ,3, 5, or 7
Related
I found this code on stackoverflow and everything works but I want to change the way it is printed. In this code, it prints everything where the value(n) is prime and up to 100. What I want to do is print the first hundred prime numbers. How do I do this? I have tried some kind of "(primes * 100)" because I thought multiplying it might work but it didn't. Thank you in advance.
def primes(n):
primeslist = [2]
for i in range (2,n):
p = 1
for j in primeslist:
if (i%j) == 0:
p = 0
break
if p == 1:
primeslist.append(i)
return primeslist
primeslist = primes(100)
print(primeslist)
You can print a slice of your list:
print(primeslist[:100])
If you want them in seperate lines:
print("\n".join([str(i) for i in primeslist[:100]]))
If you want to PRODUCE first 100 primes instead of primes up to value of 100 you must change:
for i in range (2,n):
to
while len(primeslist)<100:
If you want to print first n number of primes, this is one way of doing it.
i = 1
while True:
i += 1
p = 1
for j in primeslist:
if (i%j) == 0:
p = 0
break
if p == 1:
primeslist.append(i)
if len(primeslist) == n:
return primeslist
or this is another way of doing.
i = 1
while len(primeslist) == n:
i += 1
p = 1
for j in primeslist:
if (i%j) == 0:
p = 0
break
if p == 1:
primeslist.append(i)
return primeslist
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
So I am new to programming in python(and in general) and was doing some coding challenges. I came across this 'prime numbers using the sieve method' challenge. I have successfully managed to attempt it however I feel like my logic needs improvement.
So what I did was use 3 while loops in python, the code works as intended, gives me a set of prime numbers however I cannot find a way to condense it.
import sys
n = int(sys.argv[1])
ls = []
i = 2
while i <= n:
ls.append(i)
i += 1
i = 0
while i < len(ls):
if i == 0:
pass
else:
ls[i] = ''
i += 2
i = 1
while i < len(ls):
if i == 1:
pass
else:
ls[i] = ''
i += 3
i = 0
while i < len(ls):
if i == 0:
pass
else:
ls[i] = ''
i += 5
i = 0
primes = []
while i < len(ls):
if ls[i] != '':
primes.append(ls[i])
i += 1
for prime in primes:
print(prime,end=', ')
As the ceo of nvidia once said, 'it just works' but clearly not in the best way :D
Your code thinks 49 is prime, which is not awesome. Making a while loop for each prime just doesn't work.
Here's a simple version that does:
import math
def primesLessThan(N):
seive = [True] * N
seive[0] = seive[1] = False
for i in range(2,int(math.sqrt(N))+1):
if (seive[i]): # i is prime
for j in range(2*i,N,i): # all multiples of i >= 2i
seive[j] = False # j is composite since i is a factor
return [p for p in range(2,N) if seive[p]]
print(primesLessThan(500))
f=0
c=1
n=raw_input("Enter the value of n")
while c<n:
for i in range(2,100):
for j in range(1,i):
if i%j == 0:
f =f+1
if f == 1:
print i
c = c+1
f = 0
If n is 5 then the output should print the first 5 prime numbers.
2,3,5,7,11
You have a few mistakes. You do not parse n as integer, you have an unnecessary loop, you inistailise c with a wrong value.
Here is a corrected version
c = 0
n=int(raw_input("Enter the value of n"))
i = 2
while True:
for j in range(2,i):
if i % j == 0:
break
else:
print i
c = c + 1
if c == n:
break
i += 1
Copy of answer to this question.
You're only checking the value of count at the end of the for loop so you will always end up with the full range of 1-100 being tested. Why is the range limited to 100?
You don't need a for loop at all. Use the while loop to keep finding primes until you have num of them.
Try something like:
import math
def isPrime(num):#this function courtesy of #JinnyCho
if num == 1:
return False
if num % 2 == 0 and num > 2:
return False
for i in range(3, int(math.sqrt(num))+1, 2):
if num % i == 0:
return False
return True
def getPrimes(num):
count = 0
i = 1
highPrime = None
while count < num:
if isPrime(i):
count += 1
yield i
i += 1
n = int(raw_input("Enter the value of n: "))
list(getPrimes(n))
SPOJ Prime Generator My python code is giving a Runtime Error NZEC, why?
testcases = raw_input(" ")
def isPrime(n):
result = True
if n != 0 and n != 1 and n % 2 != 0 and n % 5 != 0 and n % 7 != 0 and n % 9 != 0:
if n > 9:
for i in range(11,n):
if isPrime(i):
if n % i == 0:
result = False
return result
else:
return result
else:
return False
for count in range(0,testcases):
m,n = raw_input(" ").split()
m = int(m)
n = int(n)
for i in range(m,n+1):
if isPrime(i):
print i
You are getting a NZEC because of extra white spaces in the input. It's not difficult to design your code to handle such cases. Take the input at once and tokenize it by white spaces. See how I have done it.
def isPrime(n):
result = True
if n != 0 and n != 1 and n % 2 != 0 and n % 5 != 0 and n % 7 != 0 and n % 9 != 0:
if n > 9:
for i in range(11,n):
if isPrime(i):
if n % i == 0:
result = False
return result
else:
return result
else:
return False
def main(): # Don't leave the code in the global namespace, it runs slower
import sys
tokenizedInput = map(int, sys.stdin.read().split()) # Read at once, tokenize
testcases = tokenizedInput[0]
readAt = 1 # Position to begin reading
for count in range(0,testcases):
m,n = tokenizedInput[readAt:readAt+2] # Read the tokenized input
for i in range(m,n+1):
if isPrime(i):
print i
print # You need to separate two outputs by a line
readAt = readAt + 2
main()
This will get you rid of the NZEC. However, your algorithm is both inefficient and incorrect. For the sample input test case of
2
1 10
3 5
Your modified code now outputs
3
3
The expected output
2
3
5
7
3
5
For every number >= 11 you are recursively calling isPrime. If the number is large enough an stack overflow error will occur.
The Prime Generator problem on SPOJ has a large number limit. Try running your program with large numbers, like 999900000 1000000000.