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:
break
if product - int(product) == 0:
print(f"{num_1}, {int(product)}")
num_1 += 1
1 Answer 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 theif/print
as well in order to see that they don't affect the loop. Better use afor
-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 yournum_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 print1, 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– GalacticPonderer2020年08月22日 16:48:41 +00:00Commented Aug 22, 2020 at 16:48
-
2\$\begingroup\$ @JKRH Try
int(num**.5)
. \$\endgroup\$superb rain– superb rain2020年08月22日 18:21:44 +00:00Commented Aug 22, 2020 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)
gives67108865
when it should give67108864
. Withisqrt
you wouldn't have that issue. \$\endgroup\$superb rain– superb rain2020年08月23日 13:33:47 +00:00Commented Aug 23, 2020 at 13:33