I am working through the project euler problems in Python 3 as a fun way to learn the language, and my solution to problem number three I feel is a little funky. The problem is to find the largest prime factor of 600851475143, and I solved it in a pretty sprawling way as follows:
#!/usr/local/bin/python3
# encoding: utf-8
# what is the largest prime factor of whatever the user types
def main():
original = int(input("Input a number: "))
if original == isPrime(original):
print(original, "is prime")
else:
print(factor(original), "is the largest prime factor of", original)
def factor(number):
nummy=2
for num in range(nummy, number):
if (number%num==0 and isPrime(num)==num):
biggest=int(num)
number=int(number/biggest)
nummy = int(biggest+2)
print("so far,",biggest, "is the biggest prime factor...")
if number < biggest:
break
return biggest
def isPrime(value):
for num in range(2, int(value**0.5)+1):
if value%num==0:
return int(value/num)
return value
if __name__ == "__main__": main()
as you can see, in my "factor" function, I tried to update the upper limit of the range in my for loop, but it didn't really work like I was expecting so I had to add the if number < biggest block to get the whole thing to run in a reasonable amount of time.
Is there a way to update the parameters of a for loop from inside the loop?
I appreciate any insight on this.
whilestatement instead offor...range....