-8
def primetest(n):

 if n<=1:
     return false
   """Test if N is prime"""
 for i in range(2,int(n/2)+1):
         if(n%i)==0:
            return false
         
    return true

Hello so above I have my code that tells you if n is prime or not by returning true or false. Now I need to write a method called primelist() which inputs a positive integer n and outputs an ordered list of primes 2 through p. Below I have added my code but when I go to test it, for example, I test primelist(7)==is_prime(7) I get false but I should be getting true.

def primelist(n):
   for i in range(2,n+1):
       if primetest(i):
         print(I,end=" ")
Mr. Discuss
  • 355
  • 1
  • 4
  • 13
Jay J
  • 1
  • 1

1 Answers1

1

In order to test if the number is prime you need to check all the integers from 2 to the square root of n. Only if for none of them, n is divisible can you be sure it's a prime number.

Also as pointed out in the comments there are some syntactic/indentation issues e.g. True and False need to be capitalized.

def primetest(n):
    # Test if N is prime
    if n <= 1:
        return False
    for i in range(2,int(n**(1/2))+1):
        if(n%i)==0:
            return False
    return True

Edit: to work for integers less than 2 you have to treat these separately.

For the 2nd part of your question primelist(7)==is_prime(7) will always be False, because you're comparing a boolean with None type (since your 2nd function doesn't actually return anything).

Also the following might give a nicer output:

def primelist(n):
    primes = []
    for i in range(2,n+1):
        if primetest(i):
            primes.append(i)
    print(*primes, sep = " ")
Mr. Discuss
  • 355
  • 1
  • 4
  • 13
  • Ok so that issue was fixed but now when I test to see if 1 is a prime it outputs true but 1 is not a prime – Jay J Feb 03 '22 at 22:52
  • If you want it to work for n <= 1 as well you need to treat these separately, as per edit – Mr. Discuss Feb 03 '22 at 22:57
  • To backup the facts on [primality of 1](https://en.wikipedia.org/wiki/Prime_number#Primality_of_one) – hc_dev Feb 03 '22 at 23:41