Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is wrong with this isPrime function?

I’m making an isPrime function. Any odd number that I put in (unless it’s 1, 2 or 3, which break it) says that it is prime even when they clearly aren’t.

from even import *

num = input("What number? ")


def isPrime(n):
   n = int(n)
   if isEven(n):
      return False

   i = 2
   while i < n:
      a = n / i
      if isinstance(a, int):
          return False

      else:
          d = n - 2
          if i == d:
              return True

          else:
              i += 1


if isPrime(num) is True:
   print(num + " is a prime number!")

if isPrime(num) is False:
   print(num + " is not a prime number!")

And the code for the isEven function is here:

def isEven(num):
    if num == 0:
        return True

    elif num % 2 == 0:
        return True

    else:
        return False

What am I doing wrong? Also, any general tips for improving my code?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here is what you meant to type. This is not the best way, but this is parallel to the approach you were taking:

def isEven(num):
    return num % 2 == 0

def isPrime(n):
    if isEven(n):
        return False

    for i in range(2,n//2):
        if n % i != 0:
            return False
    return True

num = int(input("What number? "))

if isPrime(num):
    print(num, "is a prime number!")
else:
    print(num, "is not a prime number!")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading