1

so...this is my code down below. I altered it all ways I can think of, but regardless of what I do it will ether say all the numbers are prime or all the numbers are not prime. I was hoping someone can point out the obvious error. Currently this code says all numbers are not prime. Thanks.

import math

x = int(input('Enter a number: '))

def isPrime(x):
  if x==2:
      print ("The number you entered is not Prime.")
      return

  i = 2
  x = int(math.sqrt(x)) 
  while i < x+1:
      if x%i==0:            
          print ("The number you entered is not Prime.")
          return
      i = i+1
  print ("This number is Prime")
  return

isPrime(x)
lqhcpsgbl
  • 3,694
  • 3
  • 21
  • 30
Andrew Ricci
  • 475
  • 5
  • 21

2 Answers2

3

The main bug is here:

x = int(math.sqrt(x)) 

You are altering x, so the subsequent divisibility checks incorrectly use this altered value of x.

You should store the square root in a different variable:

sqrt_x = int(math.sqrt(x)) 
while i < sqrt_x + 1:
   ...

Also, the number 2 is prime since it's only divisible by itself and one.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

the square root line should be removed, and a minor edit will make it work.

and yes, please fix your indent

import math

def isPrime(x): 

    i = 2
    #x = int(math.sqrt(x)) 
    while i < x:#x+1:
        z = x%i
        print "i: ", i, " x: ", x, "x%i: ", z
        if z==0:
            print ("The number you entered is not Prime.")
            return
        i = i+1
    print ("This number is Prime")
    return

x = int(input('Enter a number: '))
isPrime(x)
adrianX
  • 619
  • 7
  • 21