0

I am looking for a way to get the factors of a number in Python

I have tried using loops as shown in the code below. I just can't seem to find what's wrong (it'll only output "1 times X" and "X times 1" and no other factors. testNum = int(input("Enter an Integer: ")) leftNum = 1 rightNum = testNum for i in range(testNum): for i in range(testNum): if leftNum * rightNum == testNum: print("{} times {}".format(leftNum,rightNum) rightNum -= 1 leftNum += 1 (tilt device on side if lines don't show clearly)

27th Aug 2018, 4:12 PM
Trigger
Trigger - avatar
8 odpowiedzi
+ 4
There might be something wrong with the indentation. Here's a simpler way to do it: testNum = int(input()) for leftNum in range(testNum//2+1): for rightNum in range(testNum//2+1): if leftNum * rightNum == testNum: print(f'{leftNum} x {rightNum} = {testNum}') /PS This one is a lot faster for bigger numbers: testNum = int(input()) def getFactors(n): for i in range(2, int(n**.5)+1): if testNum % i == 0: yield i for f in getFactors(testNum): print(f'{f} x {int(testNum/f)} = {testNum}') (it will print each combination only once, so a * b = x, but not b * a = x)
27th Aug 2018, 5:05 PM
Anna
Anna - avatar
+ 1
Thank you Anna! Perfect👌🖖
27th Aug 2018, 5:07 PM
Trigger
Trigger - avatar
+ 1
Mayank It will only look up to the square root of the number because if you go any further, the "reverse" divisors already have been found (if there are any). If you look up to testNum//2+1, it will find both 3*4 and 4*3 for 12. If you stop at square root + 1, it will only find 3*4, but make the code much faster. You're right about the variable name.
27th Aug 2018, 6:12 PM
Anna
Anna - avatar
+ 1
Thank You
27th Aug 2018, 6:24 PM
Trigger
Trigger - avatar
+ 1
Anna oh, ok thanks i got it now
28th Aug 2018, 1:09 AM
Mayank
Mayank - avatar
0
Hi, Anna can you please help me in understanding your code? why did you do square root of testnum in the second function, how will it give all the factors? Also testnum is not defined in the function scope i think you wanted to write the parameter n there.
27th Aug 2018, 6:04 PM
Mayank
Mayank - avatar
0
So what is the code in the end? Im trying to get experience so Im gonna study this program
27th Aug 2018, 6:14 PM
Trigger
Trigger - avatar