A variant of the algorithm for iterating over dividers with c wheel factorization for factors 2 and 3 . Dividers are generated in steps of 2 and 4 in turn. Translated from D code :
from math import ceil, sqrt def mindivisor(number): # manually test 1, 2, 3 and multiples of 2 and 3 if number == 1: return 1 elif number % 2 == 0: return 2 elif number % 3 == 0: return 3 # we can now avoid to consider multiples # of 2 and 3. This can be done really simply # by starting at 5 and incrementing by 2 and 4 # alternatively, that is: # 5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, ... # we don't need to go higher than the square root of the number divisor = 5 increment = 2 sqrt_n = ceil(sqrt(number)) while divisor <= sqrt_n: if number % divisor == 0: return divisor divisor += increment increment = 6 - increment # 2 -> 4 -> 2 return number # number is prime
<script type="text/javascript" src="https://cdn.rawgit.com/brython-dev/brython/3.4.0/www/src/brython.js"></script><body onload="brython()"><script type="text/python"> from math import ceil, sqrt def mindivisor(number): # manually test 1, 2, 3 and multiples of 2 and 3 if number == 1: return 1 elif number % 2 == 0: return 2 elif number % 3 == 0: return 3 # we can now avoid to consider multiples # of 2 and 3. This can be done really simply # by starting at 5 and incrementing by 2 and 4 # alternatively, that is: # 5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, ... # we don't need to go higher than the square root of the number divisor = 5 increment = 2 sqrt_n = ceil(sqrt(number)) while divisor <= sqrt_n: if number % divisor == 0: return divisor divisor += increment increment = 6 - increment # 2 -> 4 -> 2 return number # number is prime def show(n): print(f"{n} -> {mindivisor(n)}") show(2209) show(2201) # try your own input from browser import document, alert @document["mybutton"].bind("click") def on_click(event): show(int(document["zone"].value)) </script> <input id="zone" value="2021"><button id="mybutton">mindivisor</button></body>
if i > sqrt(n)check - jfs