ホームページ  >  記事  >  ウェブフロントエンド  >  JavaScript を使用して、指定された整数の素数の合計を加算します。

JavaScript を使用して、指定された整数の素数の合計を加算します。

Susan Sarandon
Susan Sarandonオリジナル
2024-10-11 10:28:30748ブラウズ

Add the sum of prime numbers for a given integer using JavaScript

正の整数をパラメータとして受け取り、それ以下のすべての素数の合計を表示する関数を作成します。

解決

// Define a function named addPrimeSum that takes a single parameter 'number'
function addPrimeSum(number) {
  // Initialize a variable 'result' to store the sum of prime numbers, starting from 0
  let result = 0;

  // Define an inner function named isPrime that takes a single parameter 'num'
  function isPrime(num) {
    // If 'num' is less than 2, it is not prime, so return nothing (undefined)
    if (num < 2) return;

    // Loop from 2 to half of 'num' to check for factors
    for (let i = 2; i <= num / 2; i++) {
      // If 'num' is divisible by 'i', it's not prime, so return nothing (undefined)
      if (num % i === 0) return;
    }
    // If no factors are found, return 'num' indicating it is a prime number
    return num;
  }

  // Loop while 'number' is greater than 1
  while (number > 1) {
    // Check if 'number' is prime using the isPrime function
    if (isPrime(number)) {
      // If it is prime, add it to 'result'
      result += number;
    }
    // Decrement 'number' by 1 to check the next lower number
    number--;
  }

  // Return the total sum of all prime numbers found
  return result;
}

console.log(addPrimeSum(5));
console.log(addPrimeSum(21));
console.log(addPrimeSum(100));
console.log(addPrimeSum(239));
console.log(addPrimeSum(956));

解決

> 10
> 77
> 1060
> 5589
> 70241

以上がJavaScript を使用して、指定された整数の素数の合計を加算します。の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。