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:
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.
PHP: Tips of the Day
PHP: How to find the last day of the month from date?
$a_date = "2009-11-23"; echo date["Y-m-t", strtotime[$a_date]];
Ref : //bit.ly/31coSLD
I have the following code, to output all prime numbers from array. I would like to get the sum of the output in ex: 2+3+5 = 10, Any hint how to get that ?
$n = array[1,2,3,4,5,6];
function prime[$n]{
for[$i=0;$i
Output:
2
3
5
Sum: 10
answered Nov 29, 2014 at 17:26
Rizier123Rizier123
57.8k16 gold badges91 silver badges142 bronze badges
3
As @IMSoP commented above, one option is to compile the list of primes into a new array:
$m = [];
// looping code...
// If prime:
array_push[ $m, $primeNumber ];
Then, when you're done, you can do your printing mechanism:
print implode[ "
", $m ];
And then you can do your summing mechanism:
print "Sum: " . array_sum[ $m ] . "
";
The added benefit here is you can split out each piece of functionality into it's own function or method [which you should do to have a good design].
answered Nov 29, 2014 at 17:30
rockerestrockerest
10.3k3 gold badges36 silver badges67 bronze badges
1
try this