Skip to content

Instantly share code, notes, and snippets.

@sitbon
Last active November 4, 2022 03:08
Show Gist options
  • Save sitbon/833c0a523b8839ff8a4576f64df239f3 to your computer and use it in GitHub Desktop.
Save sitbon/833c0a523b8839ff8a4576f64df239f3 to your computer and use it in GitHub Desktop.
HackerRank: Project Euler 03
"""
HR: https://www.hackerrank.com/contests/projecteuler/challenges/euler003/problem
PE: https://projecteuler.net/problem=3
Discussion: https://www.hackerrank.com/contests/projecteuler/challenges/euler003/forum/comments/1195942
Some hints:
* Search backwards from what you think the largest prime factor might be.
* Start with the base case:
* If `n` is even, then you know the largest prime factor will be `<= n/2`.
* If it's odd, check against some other smaller primes that divide `n`.
* If nothing is found, subtract 2 from `n` and try again.
Furthermore, you can keep dividing by 2 (for example) until you get an odd
number. This means you can *reduce* `n` successively by 2 and its other smallest
prime factors, greatly reducing the search space.
Using 30 as an example, whose prime factors are 2, 3, and 5:
* 30 / 2 = 15
* 15 / 3 = 5 <-- largest prime factor
* 30 / 3 = 10
* 10 / 2 = 5 <--
The link below is a (Python) solution that does this while also retrying the
prime factor reduction using newly found prime numbers.
[Click here for the solution code.](https://gist.github.com/sitbon/833c0a523b8839ff8a4576f64df239f3)
It's very fast for numbers in the test case range (`10^12`), in line with
or even slightly faster than `max(sympy.primefactors(n))`.
Performance starts to degrade as the prime factors get very big, around `n = 10**50-1`.
I split the prime search which helps from there, but there are better ways to check for primality
that can be dropped in.
Here are some test cases to try for yourself before checking out the code.
```
--> Test Case 1
8
45182
28
70
359
71
77
977
77777777
--> Output:
41
7
7
359
71
11
977
137
--> Test Case 2
10
999999999997
99999999993
9999999991
999999999993
999999999991
99999999997
999999999745
9999999997
999999999989
999999999983
--> Output:
181587071
108577633
100003
211371803
1000003
5882352941
199999999949
769230769
999999999989
4366812227
```
"""
import math
from functools import cache
known_primes = {2, 3, 5, 7, 11, 13, 17}
@cache
def isprime(p):
if p & 1 == 0 or p < 2:
return False
if p in known_primes: # Needed for initial (non-cached) calls
return True
for kp in filter(lambda kpf: kpf <= p, known_primes):
if p % kp == 0:
return False
du = d_min = 3
d_max = int(math.sqrt(p))
if d_max & 1 == 0:
d_max -= 1
d_mid = d_max // 2
dd = d_max
while du <= d_mid:
if p % du == 0:
if du not in known_primes:
isprime(du)
return False
du += 2
if p % dd == 0:
if dd not in known_primes:
isprime(dd)
return False
dd -= 2
known_primes.add(p)
return True
def reduce(nn):
while 1:
nn0 = nn
if nn in known_primes:
return nn
for pp in filter(lambda ppf: ppf <= nn, set(known_primes)):
nni = nn
while nn != pp and nn % pp == 0:
nn //= pp
if nn == pp or isprime(nn):
return nn
if nn != nni:
break
if nn == nn0:
break
return nn
def largest_prime_factor(n):
nrr = nr = n
while 1:
nrn = reduce(nr)
if nrn != nr:
nr = nrn
if nrn < nrr:
nrr = nrn
while not isprime(nrr):
nrr -= 2
if n % nrr == 0:
return nrr
nrr -= 2
for _ in range(int(input().strip())):
ni = int(input().strip())
print(largest_prime_factor(ni))
# # Interactive version for testing:
#
# try:
# while 1:
# print(largest_prime_factor(int(input().strip())))
# except KeyboardInterrupt:
# pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment