Quick and easy changes:
input
should prompt what it's asking for.
- You want to encapsulate what you're doing into a function, but the function should just return, not print. But it's strange for a function to sometimes return a string and sometimes a number, so I've made it only return a number, and saved switching to "No" for the main thread to decide.
- You should document what you're doing and why. Since there's been some confusion about the greatest common factor, you should definitely document that this isn't that. Type hints are also nice. I've also included some doctest entries, so that you could run
python -m doctest -v myscript.py
and double check that it's working.
- Use an
if __name__ == '__main__'
guard
- The only point of
l1
is to get the first number. We can skip the reversing and just get the last number: cf1=l1[-1]
.
A much better change comes from realizing that factors come in pairs (with a square root paired with itself). This means that the greatest factor pairs with the least factor greater than 1:
cf1 = n1/next( n for n in range(2,n1+1) if n1%n==0 )
We could do the same thing for cf2
, which would make the function symmetric and easier to understand. But if we're desperate for that last performance boost, we can do a bit better:
If they have a common greatest factor, then it will be the greatest common factor. The Euclidean algorithm will very quickly find this value. The only thing that could mess things up would be if there is some other factor between cf
and n
. That could be a lot of numbers to check, but we can do the pairing trick again, and look for other numbers between 1
and n/cf
. If there's a factor there, then there is a greater factor than the greatest common factor, and they don't have a common greatest factor.
def commonGreatestFactor(n1:int,n2:int) -> int:
'''
Finds if the greatest factor of each number is the same, and returns it.
This is not the greatest common factor
(although if they have the same greatest factor, then it is equal to the gcf).
If they do not share the same greatest factor, this returns 0.
>>> commonGreatestFactor(3,6)
0
>>> commonGreatestFactor(6,9)
3
>>> commonGreatestFactor(12,18)
0
>>> commonGreatestFactor(15,27)
0
'''
gcf,other = n1,n2
while other:
gcf,other = other,gcf%other
if min(n1,n2)==gcf<max(n1,n2):
return 0
# if there's a factor of n1 between 1 and n1/gcf,
# then the gcf is not the greatest factor of n1
if next( (n for n in range(2,n1//gcf) if n1%n==0) , 0 ):
return 0
if next( (n for n in range(2,n2//gcf) if n2%n==0) , 0 ):
return 0
return gcf
if __name__ == '__main__':
n1=int(input('First number: '))
n2=int(input('Second number: '))
result = commonGreatestFactor(n1,n2)
if result:
print(result)
else:
print("No")