forked from TheAlgorithms/PHP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseX.php
More file actions
29 lines (24 loc) · 722 Bytes
/
BaseX.php
File metadata and controls
29 lines (24 loc) · 722 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?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));
}