w3resource

PHP Exercises: Compute sum of the prime numbers less than 100

PHP: Exercise-37 with Solution

Write a PHP program to compute the sum of the prime numbers less than 100.

Note: There are 25 prime numbers are there in less than 100.
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 and sum of all these numbers is 1060.

Sample Solution:

PHP Code:

<?php
// Array to store prime numbers
$primes = array();
// Flag to check if a number is prime
$is_prime_no = false;

// Loop to find the first 100 prime numbers
for ($i = 2; $i < 100; $i++) {
    $is_prime_no = true; 

    // Nested loop to check if $i is divisible by any number from 2 to $i/2
    for ($j = 2; $j <= ($i/2); $j++) {
        if ($i % $j == 0) {
            // If $i is divisible, it's not a prime number
            $is_prime_no = false;
            break;
        }
    }

    // If $i is a prime number, add it to the $primes array
    if ($is_prime_no) {
        array_push($primes, $i);
    }

    // If 100 prime numbers are found, exit the loop
    if (count($primes) == 100) {
        break;
    }
}

// Output the sum of the first 100 prime numbers
echo array_sum($primes) . "\n";

?>

Explanation:

  • Initialize Variables:
    • $primes is an array to store prime numbers.
    • $is_prime_no is a flag to indicate if a number is prime.
  • Loop to Find Prime Numbers:
    • A for loop iterates over numbers starting from 2, aiming to find the first 100 prime numbers.
  • Check If a Number Is Prime:
    • For each number $i, $is_prime_no is initially set to true.
    • An inner loop checks if $i is divisible by any number from 2 to $i/2.
    • If $i is divisible, $is_prime_no is set to false, indicating $i is not prime, and the inner loop breaks.
  • Store Prime Numbers:
    • If $is_prime_no is still true after the inner loop, $i is a prime number and is added to the $primes array.
    • If the $primes array contains 100 prime numbers, the loop stops.
  • Calculate and Output the Sum:
    • array_sum($primes) calculates the sum of the first 100 prime numbers, which is then printed.

Output:

1060       

Flowchart:

Flowchart: Compute sum of the prime numbers less than 100

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a PHP program to test if a given string occurs at the end of another given string.
Next: Write a PHP program to valid an email address.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php-exercises/php-basic-exercise-37.php