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.

Asked By: Xyls047

||

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.

Answered By: alexhroom
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')
Answered By: Asi
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.