w3resource

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


40. Calculate Modulus Without %

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";

?>

Explanation:

  • Define a Function to Calculate Remainder Without Using the Modulus Operator:
    • function without_mod($m, $n) defines a function that takes two integers, $m and $n, and calculates the remainder of $m divided by $n without using %.
  • Calculate Division Result:
    • (int) ($m / $n) calculates how many times $n divides into $m and stores it in $divides.
  • Calculate Remainder:
    • $m - $n * $divides returns the remainder by subtracting the product of $n and $divides from $m.
  • Test the Function:
    • echo without_mod(13, 2) prints the remainder of 13 / 2, which is 1.
    • echo without_mod(81, 3) prints the remainder of 81 / 3, which is 0.

Output:

1                                                           
0        

Flowchart:

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

For more Practice: Solve these Related Problems:

  • Write a PHP script to compute the remainder of two integers using iterative subtraction.
  • Write a PHP script to calculate modulus by leveraging floating-point division and floor functions.
  • Write a PHP function to perform modulus calculation without utilizing the % or fmod operators.
  • Write a PHP script to calculate modulus using bitwise operations where applicable.


Go to:


PREV : Get File Size.
NEXT : Multiplication Table 6x6.

PHP Code Editor:



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

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.