-1

My assignment is Create a program that checks whether a number is a prime number. The display should include whether or not the number is prime and a list of the number’s factors.For numbers that are not prime, also include the number of factors for that number. I have the code

while choice.lower() == "y":
def is_prime_number(x):
    if x >= 2:
        for y in range(2,x):
            if not ( x % y ):
                return False
    else:
            return False
    return True


for i in range(int(input("Please enter an interger between 1 and 5,000: "))):
    if is_prime_number(i):
        prime_numbers += 1
        print (i)

print (str(prime_numbers) + " is a prime number.")

the output i get is

Please enter an interger between 1 and 5,000: 22
2
3
5
7
11
13
17
19
8 is a prime number.
Continue (y/n)?: 

I need the output to be the factors of that number. Please help i am a begginer

idjaw
  • 25,487
  • 7
  • 64
  • 83
  • 1
    I don't think this is a dup of [this question](https://stackoverflow.com/questions/15285534/). The OP has a working (if inefficient) prime test function, and wants to know how to change it to a factor-counting function. Giving him a more efficient prime test function doesn't answer that. – abarnert Jun 19 '18 at 01:14

1 Answers1

1

Obviously, you can't just return False as soon as you find a factor if you're supposed to be counting the number of factors. Instead, you need to increment some count of factors and keep going through the loop:

for y in range(2,x):
    if not ( x % y ):
        factors += 1

Of course you also need code that starts off with factors = 0.

Also, you can't just return True for prime and False for composite; you have to return the number of factors as well. And, since you're no longer returning early as soon as you find a factor, you can't just return True at the end; you need to decide whether the number is prime or not based on the number of factors you've found.

More importantly, you need to return the number of factors, either instead of or in addition to returning whether the number is prime. Maybe you can just return factors. Although you need to figure out what to do about 0 and 1 now; the existing else: return False doesn't make any sense with that.

And you probably want to change your function name from is_prime_number to, say, count_factors.

And then, finally, you need to change your main loop to do something like this:

factors = count_factors(i)
if not factors: # and maybe some other condition for 0 and 1?
    print(i, 'is prime')
    prime_numbers += 1
else:
    print(i, 'has', factors, 'factors')

Hopefully this is enough for you to fill in the rest yourself.

abarnert
  • 354,177
  • 51
  • 601
  • 671