All Euler problems
Project Euler

Numbers with a Given Prime Factor Sum

Find numbers whose prime factors (with multiplicity) sum to a given value.

Source sync Apr 19, 2026
Problem #0618
Level Level 14
Solved By 1,231
Languages C++, Python
Answer 634212216
Length 118 words
dynamic_programmingmodular_arithmeticnumber_theory

Problem Statement

This archive keeps the full statement, math, and original media on the page.

Consider the numbers \(15\), \(16\) and \(18\):

\(15=3\times 5\) and \(3+5=8\).

\(16 = 2\times 2\times 2\times 2\) and \(2+2+2+2=8\).

\(18 = 2\times 3\times 3\) and \(2+3+3=8\).

\(15\), \(16\) and \(18\) are the only numbers that have \(8\) as sum of the prime factors (counted with multiplicity).

We define \(S(k)\) to be the sum of all numbers \(n\) where the sum of the prime factors (with multiplicity) of \(n\) is \(k\).

Hence \(S(8) = 15+16+18 = 49\).

Other examples: \(S(1) = 0\), \(S(2) = 2\), \(S(3) = 3\), \(S(5) = 5 + 6 = 11\).

The Fibonacci sequence is \(F_1 = 1\), \(F_2 = 1\), \(F_3 = 2\), \(F_4 = 3\), \(F_5 = 5\), ....

Find the last nine digits of \(\displaystyle \sum _{k=2}^{24}S(F_k)\).

Problem 618: Numbers with a Given Prime Factor Sum

Mathematical Analysis

Use dynamic programming: f(n)f(n) = number of integers whose prime factor sum equals nn.

Derivation

The solution follows from the mathematical analysis above.

Correctness

Theorem. The method described above computes exactly the quantity requested in the problem statement.

Proof. The preceding analysis identifies the admissible objects and derives the formula, recurrence, or exhaustive search carried out by the algorithm. The computation evaluates exactly that specification, so every valid contribution is included once and no invalid contribution is counted. Therefore the returned value is the required answer. \square

Complexity Analysis

  • Time: See implementation.
  • Space: See implementation.

Answer

634212216\boxed{634212216}

Code

Each problem page includes the exact C++ and Python source files from the local archive.

C++ project_euler/problem_618/solution.cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MOD = 1000000007;

int main() {
    int N = 100;
    vector<int> primes;
    vector<bool> sieve(N + 1, true);
    sieve[0] = sieve[1] = false;
    for (int i = 2; i <= N; i++) {
        if (sieve[i]) {
            primes.push_back(i);
            for (int j = 2*i; j <= N; j += i) sieve[j] = false;
        }
    }
    
    vector<ll> dp(N + 1, 0);
    dp[0] = 1;
    for (int p : primes) {
        for (int n = p; n <= N; n++)
            dp[n] = (dp[n] + dp[n-p] * p) % MOD;
    }
    
    ll S = 0;
    for (int p : primes)
        S = (S + dp[p]) % MOD;
    cout << S << endl;
    return 0;
}