Notsrik Notsrik - 2 months ago 29
PHP Question

Sum of Prime numbers

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<= count($n);$i++){

$counter = 0;
for($j=1;$j<=$i;$j++){

if($i % $j==0){

$counter++;
}
}

if($counter == 2){

print $i."<br/>";
}
}
}


print prime($n);

Answer

Then this should work for you:

(Here i used $sum which i initialized before the foreach loop and then used the += operator to add the sum together)

<?php

    $n = array(1,2,3,4,5,6);

    function prime($n){
        $sum = 0;
        foreach($n as $k => $v) {
            $counter = 0; 
            for($j = 1; $j <= $v; $j++) { 
                if($v % $j == 0)
                    $counter++;

            }

            if($counter == 2) {
                echo $v."<br/>";
                $sum += $v;
            }

        }
        echo "Sum: " . $sum;

    }

    prime($n);


?>

Output:

2
3
5
Sum: 10
Comments