PHP module problem

I have a problem, I'm trying to calculate what the lowest prime number is, but I don’t understand the result that PHP gives me.

If I have this number

 $number = 600851475143;

Then the module i it:

$primes = array( 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);

    foreach($primes as $key=>$value) {    
        if($number % $value == 0 ) {echo $value; break; }
    }

Why is this $ value = 3? If $ value = 3, this means that 600851475143/3 must be an integer, but it is not. So I don’t understand why if () evaluates to true?

+3
source share
3 answers

Using PHP 5.2.8, it does not work as described in the question. The modulo operator does not seem to work with large integers. You should use bc_mod(module with arbitrary precision):

<?php

$number = 600851475143;

$primes = array(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);

    foreach($primes as $key=>$value)
    {    
        if($number % $value == 0 ) {echo $value."<br/>"; }
        if(bcmod($number, $value) == 0) {echo "bcmod ".$value."<br/>"; }
    }

?>

The above code prints:

3

29th

bcmod 71

0
source

.

% 2 ^ 31 (32-) 2 ^ 63 (64-). BCMOD.

+4

I might not understand this, but modulo gives you the rest of the division, for example, 600851475143/3 - 200283825047 rest 2, and this is what it returns.

0
source

Source: https://habr.com/ru/post/1735108/


All Articles