This bit of code is looking for the pair of integers that make up a product.

You can input any integer and it returns the pairs of numbers that, when multiplied together, make it up.

I have done a pretty bad job at explaining this, but the code it pretty simple.

All comments welcome.

num = 498
num_1 = 1

while num_1 < num:
    product = num / num_1
    if product < num_1:
    if product - int(product) == 0:
        print(f"{num_1}, {int(product)}")
    num_1 += 1
  • Such while-loops that don't offer an advantage are unpythonic. And harder to understand. In your solution, the information about what the loop goes through is spread over six (!) lines. And I actually I need to read all 8 (!) lines, since I need to read the if/print as well in order to see that they don't affect the loop. Better use a for-loop, where it's all cleanly in one line.

  • If you do use such a while-loop, then there should be an empty line above your num_1 = 1, not under it. Because it belongs to the solution, not to the input.

  • Floating-point in general has precision issues, better avoid it if you can. Here it's simple to use just integers.

  • For num = 1, you don't print anything. You should print 1, 1.

  • Unless you have an actual reason for that formatting, keep it simple and don't format. If you use the output of your program as input for something else, it might also very well be easier to parse without that extra comma.

Resulting code:

from math import isqrt

num = 498

for i in range(1, isqrt(num) + 1):
    if num % i == 0:
        print(i, num // i)
  • \$\begingroup\$ I was trying to work out why this wouldn't work for me, then realised that I am running 3.7 and isqrt is new for 3.8. Do you have a workaround for 3.7 without using isqrt? \$\endgroup\$ – GalacticPonderer Aug 22 '20 at 16:48
  • 2
    \$\begingroup\$ @JKRH Try int(num**.5). \$\endgroup\$ – superb rain Aug 22 '20 at 18:21
  • \$\begingroup\$ @JKRH That btw seems to be correct until num=4,503,599,761,588,223, so presumably sufficient for you. But int((67108865**2 - 1)**.5) gives 67108865 when it should give 67108864. With isqrt you wouldn't have that issue. \$\endgroup\$ – superb rain Aug 23 '20 at 13:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.