Please have a look at my code and tell me where I am going wrong.
I am trying to solve a problem on SPOJ and the online judge gives me a runtime error (NZEC)
I am trying to solve this problem - http://www.spoj.com/problems/PRIME1/
def isprime(n):
if n < 2:
return 1
if n == 2 or n == 3:
return 0
if n % 2 == 0 or n % 3 == 0:
return 1
for i in range(5, int(n ** 0.5) + 1, 6):
if n % i == 0 or n % (i + 2) == 0:
return 1
return 0
t = int(raw_input())
for i in range(0,t):
m = int(raw_input())
n = int(raw_input())
for j in range(m,n+1):
if isprime(j) == 0:
print j
print
From my experience NZEC just means some exception along the way. Most likely input-related.
For example my input for the problems looks like:
t = int(raw_input())
data = sys.stdin.readlines()
for line in data:
n, m = map(int, line.split())
And indeed raw_input gets the whole line, which you're trying to convert to int. But the problem states both m and n are on the same line:
Input:
2
1 10
3 5
Related
def isPerfectSquare(n) :
i = 1
while(i * i<= n):
if ((n % i == 0) and (n / i == i)):
return True
i = i + 1
return False
lst=[]
n=int(input())
for i in range(0,n):
ele=int(input("Enter: "))
lst.append(ele)
for i in lst:
isPerfectSquare(i)
if (isPerfectSquare(n)):
print("Perf")
else:
print("Not")
I am a new python programmer so I am trying out different low levelled problems with a twist. I tried with for loops first but couldn't figure out how to do it with multiple inputs.
Where did I go wrong? When I input a perfect square, it's not working.
Issue is if (isPerfectSquare(n)): you were always just passing in the input and checking if that is a Perfect Square. You should be passing in each element of the list instead like this if isPerfectSquare(i):
def isPerfectSquare(n):
i = 1
while i * i <= n:
if (n % i == 0) and (n / i == i):
return True
i = i + 1
return False
lst = []
n = int(input())
for i in range(0, n):
ele = int(input("Enter: "))
lst.append(ele)
for i in lst:
if isPerfectSquare(i):
print("Perf")
else:
print("Not")
Output:
3
Enter: 1
Enter: 4
Enter: 10
Perf
Perf
Not
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
I am trying to write a program that will print all the primes within a given range. I have written it, the output is almost okay, it prints primes, but for some reason it prints 4, which is not a prime...
Any assistant will be most appreciated !
def primes():
start = int(input("Enter the starting number: "))
end = int(input("Enter the ending number: "))
num = 0
i = 0
ctr = 0
for num in range(start,end+1,1):
ctr = 0
for i in range(2,num//2,1):
if num % i == 0 :
ctr = ctr + 1
break
if (ctr==0 and num != 1):
print(num)
for i in range(2,num//2,1):
Lets check this snippet of code when num = 4,it becomes
for i in range(2,2,1):
Now we see the problem.
Solution..?
for i in range(2,(num//2)+1,1):
The following methods are all possible prime checkers you might use to check within your range:
def isPrime(Number): # slow
return 2 in [Number, 2 ** Number % Number]
def isprime(n): # out of memory errors with big numbers
"""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 squareroot 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
def is_prime(n): # Best until now
if n == 2 or n == 3:
return True
if n < 2 or n % 2 == 0:
return False
if n < 9:
return True
if n % 3 == 0:
return False
r = int(n ** 0.5)
f = 5
while f <= r:
# print '\t', f
if n % f == 0:
return False
if n % (f + 2) == 0:
return False
f += 6
return True
for i in range(2,num//2,1):
Above line is wrong. You are iterating from 2 to num / 2 - 1.
You should iterate from 2 to sqrt(num). (range(2, int(math.sqrt(n)) + 1))
Alternatively you can do a special check for 2 and modify your range to range(3, int(math.sqrt(n) + 1, 2)
i make a programe to find the number of divisor for a number with test case to submit it on the online judge so i write the code like that
num_case=int(raw_input())
num=list()
final_o=[]
for x in xrange(num_case):
num.append(int(raw_input()))
for h in num:
result=[int(h)]
for i in xrange(1, h + 1):
if h % i == 0:
result.append(i)
a=final_o.append(len(result)-1)
for ff in final_o:
print ff
in this case i make user input the number of test case for example 3 and then enter the number for example 12 7 and 36 then he get the output like this 6 2 9 that the 12 have 6 divisor number and so on this code work well but i get Memory Error when i submit it so i try to use itertools because range in for loop is small and xrange take a lot of time more than 2 second but i dont get any output code
from itertools import count
num_case=int(raw_input())
num=list()
final_o=[]
for x in xrange(num_case):
num.append(int(raw_input()))
for h in num:
result=[int(h)]
n=int(raw_input())
for i in count(1):
if n % i == 0:
result.append(i)
elif count==n+1:
break
a=final_o.append(len(result)-1)
for ff in final_o:
print ff
any one have a solution to this bug ? Note that the time for the test case 2 second and the range of the numbers is 10^9 and test case 100 How i Do that ?
def devisors_number(n):
result = 0
sqrt_n = int(n**0.5)
for i in xrange(1, sqrt_n + 1):
if n % i == 0:
result += 1
result *= 2
if sqrt_n**2 == n:
result -= 1
return result
n = int(raw_input("Enter a number: "))
d = devisors_number(n)
print "{0} has {1} devisors".format(n, d)
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.