What is the problem with my code for finding whether a number is prime or not
Question:
N = int(input())
flag = False
if N <= 2:
print('no')
for j in range(2, int(N**0.5)+1):
if N%j == 0:
flag = True
if flag == False:
print('yes')
else:
print('no')
The logic is same everywhere I saw the solution, but somehow codechef shows that it is a wrong answer, as I don’t have a pro subscription of codechef, I cannot see the failed cases.
Answers:
Welcome to StackOverflow! This code is along the right lines (although could be done far more efficiently) for any number above 2, but look at the edge cases – this script gives the result that both 1 and 0 are prime numbers.
N = int(input())
flag = False
for j in range(2, N):
if N % j == 0:
flag = True
if not flag and N > 1: # Important: 0 and 1 are not prime numbers
print('yes')
else:
print('no')
N = int(input())
flag = False
if N <= 2:
print('no')
for j in range(2, int(N**0.5)+1):
if N%j == 0:
flag = True
if flag == False:
print('yes')
else:
print('no')
The logic is same everywhere I saw the solution, but somehow codechef shows that it is a wrong answer, as I don’t have a pro subscription of codechef, I cannot see the failed cases.
Welcome to StackOverflow! This code is along the right lines (although could be done far more efficiently) for any number above 2, but look at the edge cases – this script gives the result that both 1 and 0 are prime numbers.
N = int(input())
flag = False
for j in range(2, N):
if N % j == 0:
flag = True
if not flag and N > 1: # Important: 0 and 1 are not prime numbers
print('yes')
else:
print('no')