explain please

galaxyAbstractor

Community Advocate
Community Support
Messages
5,508
Reaction score
35
Points
48
PHP:
<?php
//1. How many more loops does the program do to find all primes to 200?


$maxArr = 100;
$testRuns = 0;
$noPrimes = 0;
$jrun = 0;

for($i = 0; $i < $maxArr;$i++) {
    $primArr[$i] = $i + 1;
}

$primArr[0] = -1;

for($i = 1; $i < $maxArr;$i++) { 
    $prim = $primArr[$i];
    if($prim != -1) { 
        for($j = ($i + 1); $j < $maxArr; $j++){ //3c. How many numbers does this loop go trought. EXPLAIN WHY
        
            if(($primArr[$j] % $prim) == 0){ //3d. what does this if do?
                $primArr[$j] =-1;
            }
            $testRuns = $testRuns +1;
        }
    }
}


for($i = 0; $i < $maxArr; $i++){
    if($primArr[$i] != -1) {
        echo "$primArr[$i]<br />";
        $noPrimes = $noPrimes+1;
    }
}
echo "Antal loopar: $testRuns<br />";
echo "Antal primtal funna: $noPrimes<br />";

?>

Explain plox. I don't get it...
 

leafypiggy

Manager of Pens and Office Supplies
Staff member
Messages
3,819
Reaction score
163
Points
63
Neither do I. Just looking at the first loop confused me. It subtracts one; then adds one outside of the for(); lol.

I'm confused. xD
 

garrettroyce

Community Support
Community Support
Messages
5,609
Reaction score
252
Points
63
PHP:
<?php
//1. How many more loops does the program do to find all primes to 200?


$maxArr = 100;
$testRuns = 0;
$noPrimes = 0;
$jrun = 0;

for($i = 0; $i < $maxArr;$i++) {
    $primArr[$i] = $i + 1;
}

$primArr[0] = -1;

for($i = 1; $i < $maxArr;$i++) { //loop 99 times (1-99)
    $prim = $primArr[$i];
    if($prim != -1) { //true after $i = 0, which is always since loop starts at 1
        for($j = ($i + 1); $j < $maxArr; $j++){ //this will loop 98 times, then 97, then 96... $j is one more than $i and must be less than 100 ($maxArr) and this loop is encountered 99 times ($i from 1 to 99)
        
            if(($primArr[$j] % $prim) == 0){ //if the current number in the array is evenly divisible by ANY other number, it is not prime, change it's value to -1
                $primArr[$j] =-1;
            }
            $testRuns = $testRuns +1;
        }
    }
}


for($i = 0; $i < $maxArr; $i++){ //any value in the array NOT equal to negative one is echoed
    if($primArr[$i] != -1) {
        echo "$primArr[$i]<br />";
        $noPrimes = $noPrimes+1;
    }
}
echo "Antal loopar: $testRuns<br />";
echo "Antal primtal funna: $noPrimes<br />";

?>
Explain plox. I don't get it...

I've seen better ways to do this...

Hope this helps!
 

VPmase

New Member
Messages
914
Reaction score
1
Points
0
3c: It gets the modulus of the $prim number for any number > than $prim and if it equals 0 then $prim not prime.

garrettroyce explained it well in his comments.
 
Last edited:
Top