Need help with beginner math program

I want to print divisors of given number and print “the number is prime number” if the user gives prime number.

n = int(input("enter number "))
for x in range(2,n):
	if n % x == 0:
		print(x)
	elif n % x != 0:
		print(f"{n} is prime number") 

I’m not getting desired output.
OUTPUT WHEN NUMBER IS COMPOSITE

enter number 6
2
3
6 is prime number
6 is prime number

[Program finished]

OUTPUT WHEN NUMBER IS PRIME

enter number 5
5 is prime number
5 is prime number
5 is prime number

[Program finished]

Try walking through your program step by step for a simple input, like 4:

for x in range(2, 4):  # The range contains [2, 3].
    if 4 % x == 0:  # First loop x == 2; 4 % 2 == 0, so this block runs.
        print(x)  # 2 is printed.
    elif 4 % x != 0:  # Second loop == 3; 4 % 3 == 1 != 0, so this block runs.
        print(f"{4} is a prime number")  # 4 is a prime number is printed.

See the problem?

Thank you but I know the problem but can’t find a way to solution

You could use a flag to keep track of whether any divisors were found:

is_prime = True
for x in range(2, n):
    if n % x == 0:
        is_prime = False
        print(x)
if is_prime:
    print(f"{n} is prime")

A few other thoughts:

  • You could speed up the program by only checking for divisors up to sqrt(n)
  • Your current implementation only prints multiple divisors once, and also prints non-prime divisors. Is that intentional? (e.g. 8 == 2*2*2 prints 2 once, then 4)
1 Like
n = int(input("enter number "))
m = []
for x in range(2,n):
	if n % x == 0:
		m.append(x)
if m:
	for x in m:
		print(x)
elif not m:
	print(f"{n} is prime number")

This works as well. I recently started python and I’m new to programming language.

1 Like