Taskcore
Use big integers
Also called big integers, bignum, BigInteger, BigInt, arbitrary-precision integers, unlimited precision integers, big.Int, exact large integers.
Compute an integer that does not fit in 64 bits, exactly. Use the big integer type of the language, or an array of digit groups, and convert back to a fixed-width type with a check.
- Evidence
- Code in 10 languages
Task
Compute an integer result that is too large for a 64-bit integer, and get all of its digits.
The largest value of a 64-bit signed integer is 92233720368547758071, and the largest value of a 64-bit unsigned integer is 2^64 - 12. Many results are larger, for example 2 to the power 64, or the product of two large 64-bit values. In a fixed-width type, such a result wraps, saturates, raises an error or becomes a float with fewer digits. A big integer type has no fixed width. It uses as many digits as the value needs, so the arithmetic is exact.
The function big_power(base, exp) returns base to the power exp as decimal text:
big_power(2, 64) = "18446744073709551616"
big_power(-3, 41) = "-36472996377170786403"
big_power(1000, 200) = "1" followed by 600 zeros
The result is text, so that each language can give it back with no loss, and the checker compares it exactly. -1000 <= base <= 1000 and 0 <= exp <= 200, and any base to the power 0 is 1.
Solutions
| Language | Big integer type | Power | Back to 64 bits, with a check |
|---|---|---|---|
| Python | int |
base ** exp |
x.to_bytes(8, "big", signed=True) |
| JavaScript, TypeScript | bigint |
BigInt(base) ** BigInt(exp) |
compare with BigInt.asIntN(64, x) |
| Java | java.math.BigInteger |
BigInteger.valueOf(base).pow(exp) |
x.longValueExact() |
| C# | System.Numerics.BigInteger |
BigInteger.Pow(base, exp) |
(long)x |
| Go | math/big.Int |
new(big.Int).Exp(x, y, nil) |
x.IsInt64(), then x.Int64() |
| C, C++ | an array of limbs | repeated multiplication | compare with the text of the limit |
| Rust | an array of limbs, or u128 |
repeated multiplication | i64::try_from(x) |
| Bash | an array of limbs | repeated multiplication | none |
- Python. "Integers have unlimited precision."3 So
str(base ** exp)is the full solution. To put anintinto a fixed number of bytes, useint.to_bytes: "An OverflowError is raised if the integer is not representable with the given number of bytes"3. - JavaScript. A
bigintis the type for "integer values which are too high or too low to be represented by the number primitive"4. Write abigintliteral with a suffixn, as in2n ** 64n, or convert a number withBigInt(x)4. Abigint"cannot be mixed with a Number value in operations"4, so convert both operands to the same type first. - TypeScript. The same code as JavaScript, with the type
bigint. - Java.
BigIntegerholds "Immutable arbitrary-precision integers"5. Each operation returns a new object, andpow(int exponent)returns the value to the powerexponent5. - C#.
BigInteger"Represents an arbitrarily large signed integer"6, whose value "in theory has no upper or lower bounds"6.BigInteger.Pow"Raises a BigInteger value to the power of a specified value"6. GiveCultureInfo.InvariantCulturetoToString, so that the digits do not depend on the culture of the computer. - Go. "Package big implements arbitrary-precision arithmetic (big numbers)"7. For an operation, "the result is the receiver"7:
z.Exp(x, y, nil)setsztoxto the powery, andz.String()gives the decimal text. - Rust. The integer types of the language go up to
u128, with a maximum of 2^128 - 1, andi1282. A larger value needs more than one integer. The solution keeps the value in aVec<u32>of limbs (see below). - C, C++. The fixed-width types such as
int64_tanduint64_thave a width of "typically 8, 16, 32 or 64"1 bits. C++ has the same types in<cstdint>8. A larger value needs more than one integer, so the solution keeps the value in limbs, in amallocarray in C and in astd::vectorin C++. - Bash. Shell arithmetic "is done in the largest fixed-width integers available, with no check for overflow"9. The solution keeps the limbs in a Bash array. For interactive work,
bcis an "arbitrary-precision arithmetic language"10:echo '2^200' | bcprints all the digits. But "Very large numbers shall be split across lines with 70 characters per line in the POSIX locale"10, so join the lines before you use the text.
Limbs
Where the language has no big integer type, keep the number in an array of limbs, the least significant limb first. Each limb holds 9 decimal digits, so it is a value from 0 to 999999999 and it fits in 32 bits. To multiply the number by a small value m, multiply each limb by m, add the carry from the limb before, keep the remainder modulo 10^9 and carry the rest. A carry that is left at the end becomes a new limb. With m <= 1000, each product is less than 10^12 and fits in 64 bits.
To print the number, print the top limb as it is and each other limb with 9 digits and leading zeros (%09u in C). The limbs are decimal, so the printing needs no division.
The type in use
Python shows the difference between int and a fixed width of 64 bits:
x = 2 ** 64
print(x, x + 1)
print(3 ** 41)
try:
x.to_bytes(8, "big")
except OverflowError:
print("OverflowError")
print(len(str(1000 ** 200)))
18446744073709551616 18446744073709551617
36472996377170786403
OverflowError
601
In Go, an int64 wraps without an error, and a big.Int tells whether its value fits in an int64: "IsInt64 reports whether x can be represented as an int64"7.
package main
import (
"fmt"
"math"
"math/big"
)
func main() {
x := big.NewInt(math.MaxInt64)
x.Add(x, big.NewInt(1))
fmt.Println(x, x.IsInt64(), x.IsUint64())
y := new(big.Int).Exp(big.NewInt(2), big.NewInt(100), nil)
fmt.Println(y)
var n int64 = math.MaxInt64
n++
fmt.Println(n)
}
9223372036854775808 false true
1267650600228229401496703205376
-9223372036854775808
In Rust, u128 gives 64 more bits, and checked_pow returns None when the result does not fit:
fn main() {
println!("{:?}", 2u64.checked_pow(64));
println!("{}", 2u128.pow(64));
println!("{}", u128::MAX);
println!("{:?}", 2u128.checked_pow(128));
}
None
18446744073709551616
340282366920938463463374607431768211455
None
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
zero-exponent,zero-to-the-zero: any base to the power 0 is 1, also 0. For example,Expin Go with no modulus gives 1 wheny <= 07. The limb solutions start from the limb 1, so they give 1 too.zero-base: 0 to a positive power is 0, with no sign.minus-one-odd: -1 to an odd power is -1.negative-odd,negative-even: a negative base gives a negative result for an odd exponent only. The limb solutions compute with|base|and add the sign at the end.int64-max-plus-one: 2^63 is 1 more than the largestint64. It fits in auint64, and the native tests check this.uint64-max-plus-one: 2^64 is 1 more than the largestuint64.two-to-the-200: a result of 61 digits, with inner zeros. A limb that is printed without its leading zeros makes this result wrong.largest,smallest: 1000^200 has 601 digits, and (-1000)^199 has 597 zeros after "-1". Most of the limbs are 0.
Pitfalls
-
A fixed-width type.
2 ** 63in Bash andn++on the largestint64in Go wrap to a negative value with no error (see the Go block). Use a big integer type when the result can be larger than the type, or detect the overflow (see Detect integer overflow). -
A float in place of an integer. A JavaScript
numberis a float. A large power looks correct, but its last digits are not:
This code runs but gives a wrong answer on purpose.
console.log(2 ** 64 + 1 === 2 ** 64);
console.log(String(3 ** 41));
console.log((3n ** 41n).toString());
try {
console.log(1n + 1);
} catch (e) {
console.log(e.name);
}
true
36472996377170790000
36472996377170786403
TypeError
MDN warns that "the precision of a BigInt value may be lost when it is coerced to a Number value"4. Keep the value a bigint until the end.
- A conversion that cuts the value. In Java,
longValue()gives no error: when the value is too big for along, "only the low-order 64 bits are returned"5. UselongValueExact(), which throws anArithmeticException"If the value of this BigInteger is out of the range of the long type"5:
This code runs but gives a wrong answer on purpose.
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
BigInteger big = BigInteger.TWO.pow(64).add(BigInteger.valueOf(5));
System.out.println(big.longValue());
try {
big.longValueExact();
} catch (ArithmeticException e) {
System.out.println("ArithmeticException: " + e.getMessage());
}
}
}
5
ArithmeticException: BigInteger out of long range
The other languages have the same two kinds of conversion. In JavaScript, BigInt.asIntN "truncates a BigInt value to the given number of least significant bits"11, with no error. In C#, the explicit conversion to long throws an OverflowException when the "value is less than Int64.MinValue or is greater than Int64.MaxValue"12. In Go, test IsInt64() before Int64(), because when x does not fit, "the result is undefined"7.
-
Very long decimal text in Python. "CPython has a global limit for converting between int and str to mitigate denial of service attacks"3. The default limit is 4300 digits ("Illustrative, this is the default"3), and a longer conversion raises a
ValueError. The arithmetic itself has no limit. To print a longer value, raise the limit withsys.set_int_max_str_digits, or print the value in hexadecimal: "Hexadecimal, octal, and binary conversions are unlimited"3. -
Missing zeros in a limb. A limb of 5 is the 9 digits
000000005inside the number. Print each limb after the top limb with 9 digits and leading zeros. The casetwo-to-the-200finds this error. -
The sign of a negative base. Compute with the absolute value of the base and add
-only for an odd exponent. The C solution converts the base toint64_tbefore it negates it, so that the negation cannot overflow.
Related tasks
- Detect integer overflow: find out when a fixed-width result is wrong.
- Do integer arithmetic: the operators of fixed-width integers.
- Round a number: decimal types for values with a fraction.
See also the concepts Arbitrary-precision arithmetic, Integer representation, Integer overflow behaviour and Signed and unsigned integers.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-big-integers/.
def big_power(base: int, exp: int) -> str:
"""Returns base to the power exp as decimal text. A Python int has no
fixed width, so the result is exact."""
return str(base**exp)
test_big_power.py 48 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-big-integers/.
import sys
import pytest
from big_power import big_power
P200 = "1606938044258990275541962092341162602522202993782792835301376"
CASES = {
"small": (2, 10, "1024"),
"two-to-the-100": (2, 100, "1267650600228229401496703205376"),
"ten-to-the-30": (10, 30, "1" + "0" * 30),
"zero-exponent": (7, 0, "1"),
"zero-to-the-zero": (0, 0, "1"),
"zero-base": (0, 5, "0"),
"minus-one-odd": (-1, 199, "-1"),
"negative-odd": (-3, 41, "-36472996377170786403"),
"negative-even": (-3, 40, "12157665459056928801"),
"int64-max-plus-one": (2, 63, "9223372036854775808"),
"uint64-max-plus-one": (2, 64, "18446744073709551616"),
"two-to-the-200": (2, 200, P200),
"largest": (1000, 200, "1" + "0" * 600),
"smallest": (-1000, 199, "-1" + "0" * 597),
}
@pytest.mark.parametrize("case", CASES)
def test_big_power(case):
base, exp, want = CASES[case]
assert big_power(base, exp) == want
def test_fixed_width():
big = 2**63
assert int("9223372036854775808") == big
assert (big - 1).to_bytes(8, "big", signed=True) == b"\x7f" + b"\xff" * 7
with pytest.raises(OverflowError):
big.to_bytes(8, "big", signed=True)
assert int.from_bytes(b"\x80" + b"\x00" * 7, "big", signed=True) == -big
def test_str_digit_limit():
limit = sys.get_int_max_str_digits()
if limit:
with pytest.raises(ValueError):
str(10 ** (limit + 1))
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-big-integers/.
#pragma once
#include <cstdint>
#include <cstdio>
#include <string>
#include <vector>
// Returns base to the power exp as decimal text. -1000 <= base <= 1000.
// The digits live in base-10^9 limbs, least significant first.
inline std::string big_power(int base, int exp) {
constexpr std::uint64_t limb = 1000000000;
const std::uint64_t m = base < 0 ? -static_cast<std::int64_t>(base) : base;
std::vector<std::uint32_t> limbs{1};
for (int i = 0; i < exp; i++) {
std::uint64_t carry = 0;
for (auto &d : limbs) {
const std::uint64_t t = d * m + carry;
d = static_cast<std::uint32_t>(t % limb);
carry = t / limb;
}
if (carry != 0) {
limbs.push_back(static_cast<std::uint32_t>(carry));
}
}
std::string out = (base < 0 && exp % 2 == 1) ? "-" : "";
out += std::to_string(limbs.back());
char buf[16];
for (auto it = limbs.rbegin() + 1; it != limbs.rend(); ++it) {
std::snprintf(buf, sizeof buf, "%09u", static_cast<unsigned>(*it)); // keep the inner zeros
out += buf;
}
return out;
}
test_big_power.cpp 57 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-big-integers/.
#include "big_power.hpp"
#include <cstdint>
#include <cstdio>
#include <limits>
#include <string>
namespace {
struct TestCase {
const char *name;
int base, exp;
std::string want;
};
const TestCase cases[] = {
{"small", 2, 10, "1024"},
{"two-to-the-100", 2, 100, "1267650600228229401496703205376"},
{"zero-exponent", 7, 0, "1"},
{"zero-to-the-zero", 0, 0, "1"},
{"zero-base", 0, 5, "0"},
{"minus-one-odd", -1, 199, "-1"},
{"negative-odd", -3, 41, "-36472996377170786403"},
{"negative-even", -3, 40, "12157665459056928801"},
{"int64-max-plus-one", 2, 63, "9223372036854775808"},
{"uint64-max-plus-one", 2, 64, "18446744073709551616"},
{"two-to-the-200", 2, 200, "1606938044258990275541962092341162602522202993782792835301376"},
{"ten-to-the-30", 10, 30, "1" + std::string(30, '0')},
{"largest", 1000, 200, "1" + std::string(600, '0')},
{"smallest", -1000, 199, "-1" + std::string(597, '0')},
};
} // namespace
int main() {
int failures = 0;
for (const auto &c : cases) {
if (big_power(c.base, c.exp) != c.want) {
std::fprintf(stderr, "case %s failed\n", c.name);
failures++;
}
}
// 2^63 fits in a uint64_t but not in an int64_t.
const std::uint64_t big = static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max()) + 1;
if (std::to_string(big) != big_power(2, 63)) {
std::fprintf(stderr, "uint64 check failed\n");
failures++;
}
if (failures != 0) {
return 1;
}
std::puts("ok");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-big-integers/.
import java.math.BigInteger;
final class BigPower {
private BigPower() {}
/** Returns base to the power exp as decimal text. A BigInteger has no fixed width. */
static String bigPower(int base, int exp) {
return BigInteger.valueOf(base).pow(exp).toString();
}
}
BigPowerTest.java 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-big-integers/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.math.BigInteger;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class BigPowerTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("small", 2, 10, "1024"),
Arguments.of("two-to-the-100", 2, 100, "1267650600228229401496703205376"),
Arguments.of("ten-to-the-30", 10, 30, "1" + "0".repeat(30)),
Arguments.of("zero-exponent", 7, 0, "1"),
Arguments.of("zero-to-the-zero", 0, 0, "1"),
Arguments.of("zero-base", 0, 5, "0"),
Arguments.of("minus-one-odd", -1, 199, "-1"),
Arguments.of("negative-odd", -3, 41, "-36472996377170786403"),
Arguments.of("negative-even", -3, 40, "12157665459056928801"),
Arguments.of("int64-max-plus-one", 2, 63, "9223372036854775808"),
Arguments.of("uint64-max-plus-one", 2, 64, "18446744073709551616"),
Arguments.of(
"two-to-the-200", 2, 200, "1606938044258990275541962092341162602522202993782792835301376"),
Arguments.of("largest", 1000, 200, "1" + "0".repeat(600)),
Arguments.of("smallest", -1000, 199, "-1" + "0".repeat(597)));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void check(String name, int base, int exp, String want) {
assertEquals(want, BigPower.bigPower(base, exp), name);
}
@Test
void fixedWidth() {
BigInteger big = BigInteger.TWO.pow(63);
assertEquals(big, new BigInteger("9223372036854775808"));
assertEquals(Long.MAX_VALUE, big.subtract(BigInteger.ONE).longValueExact());
assertThrows(ArithmeticException.class, big::longValueExact);
assertEquals(Long.MIN_VALUE, big.longValue());
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-big-integers/.
#include "big_power.h"
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#define LIMB 1000000000u // each limb holds 9 decimal digits
char *big_power(int base, int exp) {
uint32_t m = base < 0 ? (uint32_t)(-(int64_t)base) : (uint32_t)base;
size_t cap = (size_t)exp + 1; // each step adds at most one limb
size_t n = 1;
uint32_t *limbs = malloc(cap * sizeof *limbs); // least significant first
char *out = malloc(2 + 9 * cap);
if (limbs == NULL || out == NULL) {
free(limbs);
free(out);
return NULL;
}
limbs[0] = 1;
for (int i = 0; i < exp; i++) {
uint64_t carry = 0;
for (size_t j = 0; j < n; j++) {
uint64_t t = (uint64_t)limbs[j] * m + carry;
limbs[j] = (uint32_t)(t % LIMB);
carry = t / LIMB;
}
if (carry != 0) {
limbs[n++] = (uint32_t)carry;
}
}
char *p = out;
if (base < 0 && exp % 2 == 1) {
*p++ = '-';
}
p += sprintf(p, "%" PRIu32, limbs[n - 1]);
for (size_t j = n - 1; j-- > 0;) {
p += sprintf(p, "%09" PRIu32, limbs[j]); // keep the inner zeros
}
free(limbs);
return out;
}
big_power.h 11 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-big-integers/.
#ifndef BIG_POWER_H
#define BIG_POWER_H
// Returns base to the power exp as decimal text in a new string, or NULL if
// memory runs out. The caller frees the string. -1000 <= base <= 1000.
char *big_power(int base, int exp);
#endif
test_big_power.c 74 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-big-integers/.
#include "big_power.h"
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct test_case {
const char *name;
int base, exp;
const char *want;
};
static const struct test_case cases[] = {
{"small", 2, 10, "1024"},
{"two-to-the-100", 2, 100, "1267650600228229401496703205376"},
{"zero-exponent", 7, 0, "1"},
{"zero-to-the-zero", 0, 0, "1"},
{"zero-base", 0, 5, "0"},
{"minus-one-odd", -1, 199, "-1"},
{"negative-odd", -3, 41, "-36472996377170786403"},
{"negative-even", -3, 40, "12157665459056928801"},
{"int64-max-plus-one", 2, 63, "9223372036854775808"},
{"uint64-max-plus-one", 2, 64, "18446744073709551616"},
{"two-to-the-200", 2, 200, "1606938044258990275541962092341162602522202993782792835301376"},
};
static int check(const char *name, int base, int exp, const char *want) {
char *got = big_power(base, exp);
int ok = got != NULL && strcmp(got, want) == 0;
if (!ok) {
fprintf(stderr, "case %s failed\n", name);
}
free(got);
return ok ? 0 : 1;
}
int main(void) {
int failures = 0;
for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
failures += check(cases[i].name, cases[i].base, cases[i].exp, cases[i].want);
}
// Long results: a one, or a minus sign and a one, then zeros.
char want[603];
want[0] = '1';
memset(want + 1, '0', 30);
want[31] = '\0';
failures += check("ten-to-the-30", 10, 30, want);
memset(want + 1, '0', 600);
want[601] = '\0';
failures += check("largest", 1000, 200, want);
want[0] = '-';
want[1] = '1';
memset(want + 2, '0', 597);
want[599] = '\0';
failures += check("smallest", -1000, 199, want);
// 2^63 fits in a uint64_t but not in an int64_t; 2^64 fits in neither.
char buf[32];
snprintf(buf, sizeof buf, "%" PRIu64, (uint64_t)INT64_MAX + 1);
failures += check("int64-max-plus-one-uint64", 2, 63, buf);
if (UINT64_MAX + (uint64_t)1 != 0) {
fprintf(stderr, "uint64 wrap failed\n");
failures++;
}
if (failures != 0) {
return 1;
}
puts("ok");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-big-integers/.
using System.Globalization;
using System.Numerics;
public static class BigMath
{
// Returns base to the power exp as decimal text. A BigInteger has no fixed width.
public static string BigPower(int @base, int exp)
{
return BigInteger.Pow(@base, exp).ToString(CultureInfo.InvariantCulture);
}
}
BigPowerTests.cs 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-big-integers/.
using System;
using System.Numerics;
using Xunit;
public sealed class BigPowerTests
{
public static TheoryData<string, int, int, string> Cases => new()
{
{ "small", 2, 10, "1024" },
{ "two-to-the-100", 2, 100, "1267650600228229401496703205376" },
{ "ten-to-the-30", 10, 30, "1" + new string('0', 30) },
{ "zero-exponent", 7, 0, "1" },
{ "zero-to-the-zero", 0, 0, "1" },
{ "zero-base", 0, 5, "0" },
{ "minus-one-odd", -1, 199, "-1" },
{ "negative-odd", -3, 41, "-36472996377170786403" },
{ "negative-even", -3, 40, "12157665459056928801" },
{ "int64-max-plus-one", 2, 63, "9223372036854775808" },
{ "uint64-max-plus-one", 2, 64, "18446744073709551616" },
{ "two-to-the-200", 2, 200, "1606938044258990275541962092341162602522202993782792835301376" },
{ "largest", 1000, 200, "1" + new string('0', 600) },
{ "smallest", -1000, 199, "-1" + new string('0', 597) },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, int @base, int exp, string want)
{
Assert.True(want == BigMath.BigPower(@base, exp), name);
}
[Fact]
public void FixedWidth()
{
BigInteger big = BigInteger.Pow(2, 63);
Assert.Equal(long.MaxValue, (long)(big - 1));
Assert.Throws<OverflowException>(() => (long)big);
Assert.Equal(9223372036854775808UL, (ulong)big);
Assert.Throws<OverflowException>(() => (ulong)(big * 2));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-big-integers/.
/**
* Returns base to the power exp as decimal text. A BigInt has no fixed width,
* so the result is exact; a number would lose digits above 2 ** 53.
* @param {number} base
* @param {number} exp
* @returns {string}
*/
export function bigPower(base, exp) {
return (BigInt(base) ** BigInt(exp)).toString();
}
big_power.test.js 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-big-integers/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { bigPower } from "./big_power.js";
const cases = [
["small", 2, 10, "1024"],
["two-to-the-100", 2, 100, "1267650600228229401496703205376"],
["ten-to-the-30", 10, 30, "1" + "0".repeat(30)],
["zero-exponent", 7, 0, "1"],
["zero-to-the-zero", 0, 0, "1"],
["zero-base", 0, 5, "0"],
["minus-one-odd", -1, 199, "-1"],
["negative-odd", -3, 41, "-36472996377170786403"],
["negative-even", -3, 40, "12157665459056928801"],
["int64-max-plus-one", 2, 63, "9223372036854775808"],
["uint64-max-plus-one", 2, 64, "18446744073709551616"],
["two-to-the-200", 2, 200, "1606938044258990275541962092341162602522202993782792835301376"],
["largest", 1000, 200, "1" + "0".repeat(600)],
["smallest", -1000, 199, "-1" + "0".repeat(597)],
];
for (const [name, base, exp, want] of cases) {
test(name, () => {
assert.equal(bigPower(base, exp), want);
});
}
test("fixed width", () => {
const big = 2n ** 63n;
assert.equal(BigInt("9223372036854775808"), big);
assert.equal(BigInt.asIntN(64, big), -big);
assert.equal(BigInt.asUintN(64, big), big);
assert.equal(Number(2n ** 64n + 1n), 2 ** 64);
assert.throws(() => BigInt(1.5), RangeError);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-big-integers/.
// Returns base to the power exp as decimal text. A bigint has no fixed width,
// so the result is exact; a number would lose digits above 2 ** 53.
export function bigPower(base: number, exp: number): string {
return (BigInt(base) ** BigInt(exp)).toString();
}
big_power.test.ts 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-big-integers/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { bigPower } from "./big_power.ts";
const cases: [string, number, number, string][] = [
["small", 2, 10, "1024"],
["two-to-the-100", 2, 100, "1267650600228229401496703205376"],
["ten-to-the-30", 10, 30, "1" + "0".repeat(30)],
["zero-exponent", 7, 0, "1"],
["zero-to-the-zero", 0, 0, "1"],
["zero-base", 0, 5, "0"],
["minus-one-odd", -1, 199, "-1"],
["negative-odd", -3, 41, "-36472996377170786403"],
["negative-even", -3, 40, "12157665459056928801"],
["int64-max-plus-one", 2, 63, "9223372036854775808"],
["uint64-max-plus-one", 2, 64, "18446744073709551616"],
["two-to-the-200", 2, 200, "1606938044258990275541962092341162602522202993782792835301376"],
["largest", 1000, 200, "1" + "0".repeat(600)],
["smallest", -1000, 199, "-1" + "0".repeat(597)],
];
for (const [name, base, exp, want] of cases) {
test(name, () => {
assert.equal(bigPower(base, exp), want);
});
}
test("fixed width", () => {
const big = 2n ** 63n;
assert.equal(BigInt("9223372036854775808"), big);
assert.equal(BigInt.asIntN(64, big), -big);
assert.equal(BigInt.asUintN(64, big), big);
assert.equal(Number(2n ** 64n + 1n), 2 ** 64);
assert.throws(() => BigInt(1.5), RangeError);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-big-integers/.
// Package bigpow computes exact integer powers with math/big.
package bigpow
import "math/big"
// BigPower returns base to the power exp as decimal text.
// A big.Int has no fixed width, so the result is exact.
func BigPower(base, exp int) string {
return new(big.Int).Exp(big.NewInt(int64(base)), big.NewInt(int64(exp)), nil).String()
}
big_power_test.go 54 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-big-integers/.
package bigpow
import (
"math"
"math/big"
"strings"
"testing"
)
var cases = []struct {
name string
base, exp int
want string
}{
{"small", 2, 10, "1024"},
{"two-to-the-100", 2, 100, "1267650600228229401496703205376"},
{"ten-to-the-30", 10, 30, "1" + strings.Repeat("0", 30)},
{"zero-exponent", 7, 0, "1"},
{"zero-to-the-zero", 0, 0, "1"},
{"zero-base", 0, 5, "0"},
{"minus-one-odd", -1, 199, "-1"},
{"negative-odd", -3, 41, "-36472996377170786403"},
{"negative-even", -3, 40, "12157665459056928801"},
{"int64-max-plus-one", 2, 63, "9223372036854775808"},
{"uint64-max-plus-one", 2, 64, "18446744073709551616"},
{"two-to-the-200", 2, 200, "1606938044258990275541962092341162602522202993782792835301376"},
{"largest", 1000, 200, "1" + strings.Repeat("0", 600)},
{"smallest", -1000, 199, "-1" + strings.Repeat("0", 597)},
}
func TestBigPower(t *testing.T) {
for _, c := range cases {
if got := BigPower(c.base, c.exp); got != c.want {
t.Errorf("%s: got %s, want %s", c.name, got, c.want)
}
}
}
func TestFixedWidth(t *testing.T) {
big63 := new(big.Int).Lsh(big.NewInt(1), 63)
if big63.IsInt64() {
t.Error("2^63 fits in an int64")
}
max := new(big.Int).Sub(big63, big.NewInt(1))
if !max.IsInt64() || max.Int64() != math.MaxInt64 {
t.Error("2^63 - 1 is not math.MaxInt64")
}
if !big63.IsUint64() || big63.Uint64() != 1<<63 {
t.Error("2^63 does not fit in a uint64")
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-big-integers/.
/// Returns `base` to the power `exp` as decimal text. -1000 <= base <= 1000.
/// The digits live in base-10^9 limbs, least significant first.
pub fn big_power(base: i32, exp: u32) -> String {
const LIMB: u64 = 1_000_000_000;
let m = u64::from(base.unsigned_abs());
let mut limbs: Vec<u32> = vec![1];
for _ in 0..exp {
let mut carry = 0u64;
for d in limbs.iter_mut() {
let t = u64::from(*d) * m + carry;
*d = (t % LIMB) as u32;
carry = t / LIMB;
}
if carry != 0 {
limbs.push(carry as u32);
}
}
let mut out = String::new();
if base < 0 && exp % 2 == 1 {
out.push('-');
}
let mut it = limbs.iter().rev();
if let Some(top) = it.next() {
out.push_str(&top.to_string());
}
for d in it {
out.push_str(&format!("{d:09}")); // keep the inner zeros
}
out
}
tests/big_power_test.rs 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-big-integers/.
use algo_use_big_integers::big_power;
#[test]
fn cases() {
let cases: Vec<(&str, i32, u32, String)> = vec![
("small", 2, 10, "1024".into()),
("two-to-the-100", 2, 100, "1267650600228229401496703205376".into()),
("ten-to-the-30", 10, 30, format!("1{}", "0".repeat(30))),
("zero-exponent", 7, 0, "1".into()),
("zero-to-the-zero", 0, 0, "1".into()),
("zero-base", 0, 5, "0".into()),
("minus-one-odd", -1, 199, "-1".into()),
("negative-odd", -3, 41, "-36472996377170786403".into()),
("negative-even", -3, 40, "12157665459056928801".into()),
("int64-max-plus-one", 2, 63, "9223372036854775808".into()),
("uint64-max-plus-one", 2, 64, "18446744073709551616".into()),
("two-to-the-200", 2, 200, "1606938044258990275541962092341162602522202993782792835301376".into()),
("largest", 1000, 200, format!("1{}", "0".repeat(600))),
("smallest", -1000, 199, format!("-1{}", "0".repeat(597))),
];
for (name, base, exp, want) in cases {
assert_eq!(big_power(base, exp), want, "{name}");
}
}
#[test]
fn fixed_width() {
assert_eq!(2i64.checked_pow(63), None);
assert_eq!(2u128.pow(64).to_string(), big_power(2, 64));
assert_eq!(2u128.pow(127).to_string(), big_power(2, 127));
assert!(u64::try_from(2u128.pow(64)).is_err());
assert!(i64::try_from(2u128.pow(63)).is_err());
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-big-integers/.
# big_power BASE EXP
# Prints BASE to the power EXP as decimal text. -1000 <= BASE <= 1000.
# Bash arithmetic uses fixed-width integers with no overflow check, so the
# function keeps the digits in an array of base-10^9 limbs, least
# significant first.
big_power() {
local base=$1 exp=$2 m i j t carry out
local -a limbs=(1)
m=$(( base < 0 ? -base : base ))
for (( i = 0; i < exp; i++ )); do
carry=0
for (( j = 0; j < ${#limbs[@]}; j++ )); do
t=$(( limbs[j] * m + carry ))
limbs[j]=$(( t % 1000000000 ))
carry=$(( t / 1000000000 ))
done
if (( carry > 0 )); then
limbs+=("$carry")
fi
done
out=""
if (( base < 0 && exp % 2 == 1 )); then
out="-"
fi
j=$(( ${#limbs[@]} - 1 ))
out+=${limbs[j]}
for (( j = j - 1; j >= 0; j-- )); do
printf -v t '%09d' "${limbs[j]}" # keep the inner zeros
out+=$t
done
printf '%s\n' "$out"
}
test_big_power.bats 35 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-big-integers/.
setup() {
source "$BATS_TEST_DIRNAME/big_power.sh"
}
check() { # check WANT BASE EXP
local got
got=$(big_power "$2" "$3")
[ "$got" = "$1" ] || { printf 'got: %s\nwant: %s\n' "$got" "$1"; return 1; }
}
zeros() { printf '%0*d' "$1" 0; }
@test "small" { check 1024 2 10; }
@test "two-to-the-100" { check 1267650600228229401496703205376 2 100; }
@test "ten-to-the-30" { check "1$(zeros 30)" 10 30; }
@test "zero-exponent" { check 1 7 0; }
@test "zero-to-the-zero" { check 1 0 0; }
@test "zero-base" { check 0 0 5; }
@test "minus-one-odd" { check -1 -1 199; }
@test "negative-odd" { check -36472996377170786403 -3 41; }
@test "negative-even" { check 12157665459056928801 -3 40; }
@test "int64-max-plus-one" { check 9223372036854775808 2 63; }
@test "uint64-max-plus-one" { check 18446744073709551616 2 64; }
@test "two-to-the-200" { check 1606938044258990275541962092341162602522202993782792835301376 2 200; }
@test "largest" { check "1$(zeros 600)" 1000 200; }
@test "smallest" { check "-1$(zeros 597)" -1000 199; }
@test "plain arithmetic wraps" {
[ "$(( 2 ** 63 ))" = "-9223372036854775808" ]
[ "$(( 2 ** 64 ))" = "0" ]
}
References
- Fixed width integer types, C reference, cppreference.com, Types; Example
- Numeric types, The Rust Reference, Integer types
- Built-in Types, Python 3 documentation, Numeric Types; int.to_bytes; Integer string conversion length limitation
- BigInt, MDN Web Docs, the introduction; Description
- BigInteger, Java SE 27 API, the class description; pow, longValue, longValueExact
- BigInteger Struct, .NET API reference, Microsoft Learn, the definition; Pow; Remarks
- big, Go standard library, Overview; func (*Int) Exp, IsInt64, IsUint64
- Fixed width integer types, C++ reference, cppreference.com, Types; Example
- Bash Reference Manual, version 5.3, 6.5 Shell Arithmetic
- bc, The Open Group Base Specifications Issue 8, NAME; DESCRIPTION; EXTENDED DESCRIPTION
- BigInt.asIntN(), MDN Web Docs, the introduction
- BigInteger.Explicit Operator, .NET API reference, Microsoft Learn, Explicit(BigInteger to Int64), Exceptions
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 5TBHF2 Edit this page History Report an error Markdown