Home > other >  Divide a number up to 0 in PHP
Divide a number up to 0 in PHP

Time:07-28

What i am trying to do is divide a number by 2 get the whole number and store the remainder in another variable which i did, but the number should stop dividing until the result gets to 0 Example:

75 / 2 = 37

37 / 2 = 18

. . . .

1 / 2 = 0

This is what i have to far

$num = 75;

$n = (int) ($num / 2); //Get the whole number
$r = $num % 2; //Get the remainder 

echo $n . "<br>" . $r;

I know i have to use a loop but i am still new to this so i need help.

CodePudding user response:

Please try something like this:

<?php
$num = 75;
$divNum = 2;
while($num > 0){
$newNumber = (int) ($num / $divNum); //Get the whole number
$remainder = $num % $divNum; //Get the remainder 
$num = $newNumber;
echo $newNumber . " " . $remainder."<br>" ;
}
?> 

Output Look like this :

37 1
18 1
9 0
4 1
2 0
1 0
0 1
  • Related