Project Euler in C
All Files Functions Macros Pages
Macros | Functions
0003.c File Reference

Largest prime factor of 600851475143. More...

#include <stdint.h>
#include <stdio.h>

Go to the source code of this file.

Macros

#define MAX_PRIME_FACTOR_COUNT   64
 The size of the array to store prime factors.
 

Functions

int factor (int64_t n, int64_t prime_factors[])
 Factors an integer into primes.
 
int main (void)
 

Detailed Description

Largest prime factor of 600851475143.

https://projecteuler.net/problem=3

Definition in file 0003.c.

Macro Definition Documentation

◆ MAX_PRIME_FACTOR_COUNT

#define MAX_PRIME_FACTOR_COUNT   64

The size of the array to store prime factors.

We have Omega(n) <= log2(n), where Omega(n) is the number of prime factors (including duplicates) of a positive integer n, because:

n = p_1 p_2 ... p_k >= 2*2*...*2 = 2^k,

where k = Omega(n). Since the maximum value of an int64_t is exactly 2^63 - 1, a size of 64 is sufficient.

Definition at line 19 of file 0003.c.

Function Documentation

◆ factor()

int factor ( int64_t  n,
int64_t  prime_factors[] 
)

Factors an integer into primes.

Parameters
nAn integer > 1.
prime_factorsAn array to store the prime factors of n. The results are in order from smallest to largest.
Returns
The number of prime factors of n.

Definition at line 42 of file 0003.c.

42 {
43 int count = 0;
44
45 /* Performs trial division by the integers from 2 to `n` - 1. */
46 int64_t i;
47 for (i = 2; i < n; i++) {
48 while (n % i == 0) {
49 prime_factors[count++] = i;
50 n /= i;
51 }
52 }
53
54 if (n != 1) {
55 prime_factors[count++] = n;
56 }
57
58 return count;
59}

◆ main()

int main ( void  )

Definition at line 23 of file 0003.c.

23 {
24 int64_t prime_factors[MAX_PRIME_FACTOR_COUNT];
25
26 /* Factors 600851475143. */
27 const int count = factor(600851475143, prime_factors);
28
29 /* FIXME: No portable way to print an `int64_t`. */
30 printf("%ld\n", (long)prime_factors[count - 1]);
31
32 return 0;
33}
int factor(int64_t, int64_t[])
Factors an integer into primes.
Definition 0003.c:42
#define MAX_PRIME_FACTOR_COUNT
The size of the array to store prime factors.
Definition 0003.c:19