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";
?>
Sample Output:
1060
Flowchart:
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics