Home > Net >  How to remove redundant multiplication in a factor table?
How to remove redundant multiplication in a factor table?

Time:11-05

I am creating a code that takes the factors of a number, this is my code:

num = int(input("Enter num: "))
for i in range(1, num, 1):
  if num % i ==0:
    print(i,"*", num/i, "=", num)

What happened was that the code worked, but if I entered a number like

10, it would result in
1*10=10
2*5 = 10
5*2 = 10, 2*5 and 5*2 are the same

, and the second part of the output is essentially redundant. How should I remove this part?

CodePudding user response:

As @InSync says in their comment, you should iterate up to the square root of the number.

from math import sqrt
num = int(input("Enter num: "))
for i in range(1, int(sqrt(num))   1, 1):
  if num % i ==0:
    print(i,"*", num/i, "=", num)

By going up to the square root, you will avoid going over factors again. For example, since the square root of 10 is about 3.2, the last number your loop will check is 3. This will prevent 5 from being checked, since it would already be seen when checking 2.

CodePudding user response:

just stop once you get a quotient which is less than divisor:

for i in range(1, num):
    if num % i == 0:
        j = num // i
        if j < i:
            break
        print(i,"*", j, "=", num)
  • Related