-1

I'm working on Project Euler problem 3, but my code gives a weird error. The error is:

Fatal error: Can't use function return value in write context in D:\Google Drive\ITvitae\PHP5\ProjectEuler\PE3-PrimeFactor2.php on line 52

This is the code I'm running:

<html>
<body>

<?php

ini_set('memory_limit', '1024M');
ini_set('set_time_limit', '120');

$max = 1000000;
#$max = 600851475143;
$primes = array();

// Define sqrt ceiling
$maxSqrt = ceil(sqrt($max));


function isPrime($num) {
    // 1 is not prime
    if ($num == 1)
        return false;

    // 2 is prime
    if ($num == 2)
        return true;

    // Removes all even numbers
    if ($num % 2 == 0) {
        return false;
    }

    // Check odd numbers, if factor return false
    // The sqrt can be an aproximation, round it to the next highest integer value.
    $ceil = ceil(sqrt($num));

    for ($i = 3; $i <= $ceil; $i = $i + 2) {
        if($num % $i == 0)
            return false;
    }

    return true;
}

//Push latest prime into array
for ($i = 2; $i <= $maxSqrt; $i++) {
    if (isPrime($i)) {
        array_push($primes, $i);
    }
}

// Check whether $max is divisible by $primes($j)
for ($j = 0; $j <= count($primes); $j++) {
    if ($max % $primes($j) = 0) {
        $max = $max / $primes($j);
    }
}

//echo "<pre>";
//var_dump($primes);
//echo "</pre>";

echo array_pop($primes);

?>

</body>
</html>

Line 52 being

if ($max % $primes($j) = 0) {

Under // Check whether $max is divisible by $primes($j)

I've never seen this error before, and I don't understand why it's giving it. In my head, the logic is flawless (which inevitably, therefore it isn't). What is going wrong here?

EDIT: Changed it to

if ($max % $primes($j) == 0) {

But it tells me the Function name must be a string. I don't understand.

Sander
  • 1
  • 3

1 Answers1

0

The first problem was, you used = for comparison. = is an assignment and you couldn't assign a value to an expression (that wouldn't have a usefull meaning..)

Second, you have to use [] for array access, instead of (). Using () after an identifier or var always tries to call an function. In your case $primes is an array, which isn't a function.

Third, you should fix the of-by-one array access error in your for-loop.

for ($j = 0; $j < count($primes); $j++) { // < instead of <=
    if ($max % $primes[$j] == 0) { // == instead of = and [] instead of ()
        $max = $max / $primes[$j]; // again [] instead of ()
    }
}
Philipp
  • 15,377
  • 4
  • 35
  • 52
  • Thanks! I overlooked the <= and got multiple problems because of it. Tried to solve it in a weird way, but this makes much more sense. – Sander Feb 25 '17 at 11:37