freeCodeCamp/curriculum/challenges/japanese/10-coding-interview-prep/project-euler/problem-77-prime-summations.md

2.1 KiB

id title challengeType forumTopicId dashedName
5900f3b91000cf542c50fecc 問題 77: 素数の和 5 302190 problem-77-prime-summations

--description--

10 を素数の和として表す方法はちょうど 5 通りあります。

7 + 3
5 + 5
5 + 3 + 2
3 + 3 + 2 + 2
2 + 2 + 2 + 2 + 2

素数の和として表す方法が n 通りより多くなる、最初の数を求めなさい。

--hints--

primeSummations(5) は数値を返す必要があります。

assert(typeof primeSummations(5) === 'number');

primeSummations(5)11 を返す必要があります。

assert.strictEqual(primeSummations(5), 11);

primeSummations(100)31 を返す必要があります。

assert.strictEqual(primeSummations(100), 31);

primeSummations(1000)53 を返す必要があります。

assert.strictEqual(primeSummations(1000), 53);

primeSummations(5000)71 を返す必要があります。

assert.strictEqual(primeSummations(5000), 71);

--seed--

--seed-contents--

function primeSummations(n) {

  return true;
}

primeSummations(5);

--solutions--

function primeSummations(n) {
  function getSievePrimes(max) {
    const primesMap = new Array(max).fill(true);
    primesMap[0] = false;
    primesMap[1] = false;
    const primes = [];

    for (let i = 2; i < max; i += 2) {
      if (primesMap[i]) {
        primes.push(i);
        for (let j = i * i; j < max; j += i) {
          primesMap[j] = false;
        }
      }
      if (i === 2) {
        i = 1;
      }
    }
    return primes;
  }

  const MAX_NUMBER = 100;
  const primes = getSievePrimes(MAX_NUMBER);

  for (let curNumber = 2; curNumber < MAX_NUMBER; curNumber++) {
    const combinations = new Array(curNumber + 1).fill(0);
    combinations[0] = 1;
    for (let i = 0; i < primes.length; i++) {
      for (let j = primes[i]; j <= curNumber; j++) {
        combinations[j] += combinations[j - primes[i]];
      }
    }
    if (combinations[curNumber] > n) {
      return curNumber;
    }
  }

  return false;
}