mirror of
https://github.com/TheAlgorithms/PHP.git
synced 2025-07-10 11:36:21 +02:00
* Create BaseX.php This function let's you calculate base X of any number <11 * Update BaseX.php * Update DIRECTORY.md * Update BaseX.php * Update BaseX.php * Update DIRECTORY.md Co-authored-by: Brandon Johnson <darwinz> * Update MathsTest.php * Update tests/Maths/MathsTest.php Co-authored-by: Brandon Johnson <darwinz> * Update MathsTest.php * Update tests/Maths/MathsTest.php Co-authored-by: Brandon Johnson <darwinz> * Update tests/Maths/MathsTest.php Co-authored-by: Brandon Johnson <darwinz> --------- Co-authored-by: Brandon Johnson <darwinz>
30 lines
722 B
PHP
30 lines
722 B
PHP
<?php
|
|
|
|
/*
|
|
* This function will calculate the base of any number that is <11.
|
|
* You can calculate binary, octal quickly with this as well.
|
|
* For example, to calculate binary of number 4 you can run "echo baseX(4, 2);"
|
|
* and for octal of number 10 you can run "echo baseX(10, 8);"
|
|
*
|
|
* @param int $k The number to convert
|
|
* @param int $x The base to convert to
|
|
* @return string The base-x representation of the given number
|
|
* @author Sevada797 https://github.com/sevada797
|
|
|
|
*/
|
|
function baseX($k, $x)
|
|
{
|
|
$arr = [];
|
|
|
|
while (true) {
|
|
array_push($arr, $k % $x);
|
|
$k = ($k - ($k % $x)) / $x;
|
|
|
|
if ($k == 0) {
|
|
break;
|
|
}
|
|
}
|
|
|
|
return implode("", array_reverse($arr));
|
|
}
|