Skip to content

Commit cdbeae3

Browse files
committed
PHP Big Integer Implementation
- Power Prime number generation - Sieve
1 parent 34f71dd commit cdbeae3

File tree

1 file changed

+27
-6
lines changed

1 file changed

+27
-6
lines changed

Algorithms/Numbers-Maths/BigNumber.php

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
*/
88

99

10-
1110
class BigInteger
1211
{
1312

@@ -44,7 +43,8 @@ public function __construct(string $number)
4443
if ($number == "0") $this->lastDigit = 0;
4544
}
4645

47-
public static function print(BigInteger &$n) {
46+
public static function print(BigInteger &$n)
47+
{
4848
if ($n->signBit == BigInteger::MINUS) echo "- ";
4949
for ($i = $n->lastDigit; $i >= 0; $i--)
5050
echo $n->digits[$i];
@@ -242,12 +242,13 @@ public static function divide(BigInteger &$a, BigInteger &$b, BigInteger &$c)
242242
$b->signBit = $bsign;
243243
}
244244

245-
public static function factorial (int $n, BigInteger &$c) {
245+
public static function factorial(int $n, BigInteger &$c)
246+
{
246247

247248
BigInteger::toBigInteger("1", $c);
248249

249-
if($n > 0) {
250-
for($i = 1;$i<=$n;$i++) {
250+
if ($n > 0) {
251+
for ($i = 1; $i <= $n; $i++) {
251252
$tmp = clone $c;
252253
$number = new BigInteger($i);
253254
$result = new BigInteger("0");
@@ -258,8 +259,23 @@ public static function factorial (int $n, BigInteger &$c) {
258259
BigInteger::zeroJustify($c);
259260
}
260261

261-
}
262+
public static function power(BigInteger &$a, int $n, BigInteger &$c)
263+
{
262264

265+
BigInteger::toBigInteger("1", $c);
266+
267+
if ($n > 0) {
268+
for ($i = 0; $i < $n; $i++) {
269+
$tmp = clone $c;
270+
$result = new BigInteger("0");
271+
BigInteger::multiply($a, $tmp, $result);
272+
$c = $result;
273+
}
274+
}
275+
BigInteger::zeroJustify($c);
276+
}
277+
278+
}
263279

264280

265281
$first = new BigInteger("1234567812345678123456781234567812345678");
@@ -281,6 +297,11 @@ public static function factorial (int $n, BigInteger &$c) {
281297
BigInteger::divide($first, $second, $divide);
282298
BigInteger::print($divide);
283299

300+
$number = new BigInteger("55");
301+
$power = new BigInteger("0");
302+
BigInteger::power($number, 5, $power);
303+
BigInteger::print($power);
304+
284305
$factorial = new BigInteger("0");
285306
BigInteger::factorial(100, $factorial);
286307
BigInteger::print($factorial);

0 commit comments

Comments
 (0)