Largest Prime Factor
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143?
Implementations
// https://projecteuler.net/problem=3
// The prime factors of 13195 are 5, 7, 13 and 29.//// What is the largest prime factor of the number 600851475143
// Answer: 6857
#include <iostream>#include <cstdint>
using namespace std;
uint64_t largest_prime_factor(uint64_t number){ uint64_t answer = 1; uint64_t point = 3; uint64_t divisor = number;
while (divisor % 2 == 0) { answer = 2; divisor = divisor/2; }
while (divisor != 1) { while (divisor % point == 0) { answer = point; divisor = divisor/point; } point += 2; }
return answer;}
#if ! defined UNITTEST_MODEint main(int argc, char const *argv[]){ std::cout << "Answer: " << largest_prime_factor(600851475143) << std::endl;}#endif // #if ! defined UNITTEST_MODESolution Notes
Mathematical Background
Prime factorization is the process of determining which prime numbers multiply together to make the original number. The Fundamental Theorem of Arithmetic states that every integer greater than 1 is either prime itself or can be represented as a unique product of prime numbers (up to the order of factors).
For a number n, if it has prime factors p₁, p₂, …, pk, then n = p₁^a₁ × p₂^a₂ × … × pk^ak. The largest prime factor is the largest prime in this factorization.
Algorithm Analysis
The implementations use trial division: systematically testing divisibility by potential prime factors. Key optimizations include:
- Even factor handling: First divide out all factors of 2 (the only even prime)
- Odd factor testing: Test only odd numbers starting from 3
- Early termination: Stop checking when the remaining divisor becomes 1
- Square root bound: Only test factors up to √n, as any factor larger than √n must pair with a factor smaller than √n
Time complexity is O(√n) in the worst case, which is efficient for numbers up to ~10^18 (√n ≈ 10^9 operations).
Key Insights
- The algorithm finds all prime factors but only tracks the largest one
- Dividing out factors as they’re found reduces the number that needs checking
- For very large numbers, more advanced methods like Pollard’s rho algorithm may be needed
- The remaining number after dividing out smaller factors must be the largest prime factor (if > 1)
- This problem demonstrates why prime factorization is computationally intensive for cryptography
Educational Value
This problem teaches fundamental concepts in:
- Number theory and prime numbers
- The efficiency of different factorization algorithms
- The importance of mathematical bounds (√n) in algorithm design
- Handling large integers in different programming languages
- The relationship between trial division and more advanced factorization methods
- Why prime factorization forms the basis of modern cryptography (RSA)