w3resource

PHP Exercises: Calculate the mod of two given integers without using any inbuilt modulus operator

PHP: Exercise-40 with Solution

Write a PHP program to calculate the mod of two given integers without using any inbuilt modulus operator.

Sample Solution:

PHP Code:

<?php
// Function to calculate the remainder without using the modulus operator
function without_mod($m, $n)
{
    // Calculate how many times $n divides into $m
    $divides = (int) ($m / $n);
    
    // Calculate the remainder without using the modulus operator
    return $m - $n * $divides;
}

// Example usage of the function with inputs (13, 2)
echo without_mod(13, 2) . "\n";

// Example usage of the function with inputs (81, 3)
echo without_mod(81, 3) . "\n";

?>

Sample Output:

1                                                           
0        

Flowchart:

Flowchart: Calculate the mod of two given integers without using any inbuilt modulus operator.

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a PHP program to get the size of a file.
Next: Write a PHP program to print out the multiplication table upto 6*6.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.