Taskintro
Do integer arithmetic
Also called integer operators, arithmetic operators, integer division, remainder operator, modulo operator, power operator, exponentiation, divmod.
Add, subtract, multiply, divide, take the remainder and raise to a power with integers. The division, the remainder and the power differ most between languages.
- Evidence
- Code in 10 languages
Task
Apply the six integer operations to two integers a and b and a small exponent n: the sum, the difference, the product, the quotient, the remainder and the power.
The function arith(a, b, n) returns a list of six values: a + b, a - b, a * b, the quotient q of a divided by b rounded toward zero, the remainder a - b * q, and a to the power n. For example, arith(7, 2, 3) is [9, 5, 14, 3, 1, 343], and arith(-7, 2, 3) is [-5, -9, -14, -3, -1, -343].
The sum, the difference and the product are the same in each language, while the results fit in the type. Three operations differ:
- Division. Most languages round the integer quotient toward zero, so -7 divided by 2 is -3. Python rounds toward minus infinity, so
-7 // 2is -4. JavaScript has no integer division:7 / 2is 3.5. - Remainder. The remainder goes with the division. With the quotient rounded toward zero, the remainder has the sign of the dividend
a. With the floor quotient of Python, it has the sign of the divisorb. See Integer division and modulo. - Power. Python, JavaScript and Bash have the operator
**. Java, C, C++, C# and Go have no power operator for integers, and their power function works on floats. In several of them,^is the bitwise exclusive or, not a power.
The contract keeps a and b from -100000 to 100000 and n from 0 to 3, so each result is exact in a 64-bit integer and in a JavaScript number. For larger values, see Detect integer overflow and Use big integers. The divisor is never 0; see Detect division by zero.
Solutions
| Language | Quotient | Remainder | Power |
|---|---|---|---|
| Python | // rounds down; the solution divides the magnitudes |
a - b * q |
a ** n |
| JavaScript, TypeScript | Math.trunc(a / b) |
a % b |
a ** n |
| Java | a / b |
a % b |
a loop; Math.pow takes double values |
| C, C++ | a / b |
a % b |
a loop; pow takes double values |
| C# | a / b |
a % b |
a loop; Math.Pow takes double values |
| Go | a / b |
a % b |
a loop; math.Pow takes float64 values |
| Rust | a / b |
a % b |
a.pow(n) |
| Bash | $((a / b)) |
$((a % b)) |
$((a ** n)) |
- Python.
x // yis the "floored quotient of x and y"1: "The result is always rounded towards minus infinity"1. The contract asks for the quotient rounded toward zero, so the solution divides the absolute values and sets the sign after.x ** ygives "x to the power y"1, and the result is an exactint. - JavaScript.
a / bdivides two numbers and gives a float, so the solution rounds it withMath.trunc. The remainder operator%"always takes the sign of the dividend"2. The operator**"returns the result of raising the first operand to the power of the second operand"3. - TypeScript. The same code as JavaScript, with the type
number. - Java. "Integer division rounds toward 0"4. Java has no power operator.
Math.pow"Returns the value of the first argument raised to the power of the second argument"5, but its arguments and its result aredoublevalues. The solution multiplies in a loop. - C. For integer operands, the quotient is "truncated towards zero"6.
pow"Computes the value of base raised to the power exponent"7 fordoublevalues, so the solution uses a loop. - C++. The same operators as C, in a
constexprfunction that returns astd::array. - C#. The quotient of two integers "equals the quotient of the two operands rounded toward zero"8.
Math.Pow"Returns a specified number raised to the specified power"9, as adouble, so the solution uses a loop. - Go. The quotient is "truncated towards zero"10.
math.Pow"returns x**y, the base-x exponential of y"11 forfloat64values, so the solution uses a loop. - Rust. "Integer division rounds towards zero"12, and "the remainder will have the same sign as the dividend"12.
i64::pow"Raises self to the power of exp"13 with an exact integer result. - Bash. Arithmetic expansion has
**for "exponentiation"14, and "The operators and their precedence, associativity, and values are the same as in the C language"14.
The Python operators, and the truncated division of the contract:
a, b = -7, 2
print(a + b, a - b, a * b, a // b, a % b, a**3)
print(divmod(a, b))
q = abs(a) // abs(b) * (1 if (a < 0) == (b < 0) else -1)
print(q, a - b * q)
-5 -9 -14 -4 1 -343
(-4, 1)
-3 -1
The same values in JavaScript, where / gives a float:
const a = -7;
const b = 2;
console.log(a + b, a - b, a * b, a / b, Math.trunc(a / b), a % b, a ** 3);
-5 -9 -14 -3.5 -3 -1 -343
In C, / and % round toward zero for each sign:
#include <stdio.h>
int main(void) {
int pairs[4][2] = {{7, 2}, {-7, 2}, {7, -2}, {-7, -2}};
for (int i = 0; i < 4; i++) {
int a = pairs[i][0], b = pairs[i][1];
printf("%2d / %2d = %2d, %2d %% %2d = %2d\n", a, b, a / b, a, b, a % b);
}
}
7 / 2 = 3, 7 % 2 = 1
-7 / 2 = -3, -7 % 2 = -1
7 / -2 = -3, 7 % -2 = 1
-7 / -2 = 3, -7 % -2 = -1
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
small,exact-division: positive values, with and without a remainder.negative-dividend,negative-divisor,both-negative: the quotient rounds toward zero, and the remainder has the sign ofa.zero-dividend: 0 divided by a number is 0, and0 ** 0is 1.zero-power: each number to the power 0 is 1.divisor-larger: when|b| > |a|, the quotient is 0 and the remainder isa.largest,smallest: the largest product is 10 to the power 10, and the largest power is 10 to the power 15. Both are safe integers in JavaScript15.
Pitfalls
^is not a power. In Python, JavaScript, Go and Bash,^is the bitwise exclusive or. Python listsx ^ yas the "bitwise exclusive or of x and y"1, JavaScript has "The bitwise XOR"16 operator, Go lists^as "bitwise XOR"10, and Bash lists^as "bitwise exclusive OR"14. So2 ^ 3is 1, not 8:
This code runs but gives a wrong answer on purpose.
print(2 ^ 3, 2**3)
print(10 ^ 2, 10**2)
1 8
8 100
- A float power is not exact for large results. A
doubleholds every integer from -(2 to the power 53 - 1) to 2 to the power 53 - 1 exactly, but not every integer outside this range. These are the safe integers of JavaScript, and each one "can be exactly represented as an IEEE-754 double precision number"15. In Java,(long) Math.pow(3, 39)is not 3 to the power 39, because thedoubleresult is rounded. A loop of integer products is exact while it does not overflow:
This code runs but gives a wrong answer on purpose.
public class Main {
public static void main(String[] args) {
long loop = 1;
for (int i = 0; i < 39; i++) {
loop *= 3;
}
System.out.println((long) Math.pow(3, 39));
System.out.println(loop);
}
}
4052555153018976256
4052555153018976267
-
Python
//and%are not truncated division. Code that is moved from C or Java to Python gives other results for negative values:-7 // 2is -4 and-7 % 2is 1 in Python, but -3 and -1 in C. Usemath.trunc(a / b)only for small values, becausea / bis a float division. -
JavaScript integers above the safe integers are not exact. The operators work on 64-bit floats15. For larger integers, use
BigIntvalues. With them, division "truncates fractional components towards zero"17, so7n / 2nis3n. -
The operators can overflow. In a fixed-width type,
+,-,*and the power can give a result that does not fit. Each language has its own rule (see Integer overflow behaviour), and Detect integer overflow shows how to check.
Related tasks
- Detect integer overflow: check a result that does not fit.
- Detect division by zero: check the divisor.
- Use big integers: integers of any size.
- Round a number: rounding a float quotient.
See also the concepts Integer division and modulo, Integer overflow behaviour and Integer representation.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/do-integer-arithmetic/.
def arith(a: int, b: int, n: int) -> list[int]:
"""Returns the sum, the difference, the product, the quotient rounded
toward zero, the remainder with the sign of a, and a to the power n."""
# Python // rounds toward minus infinity and % takes the sign of b. The
# contract asks for truncated division, so divide the magnitudes and set
# the sign after.
q = abs(a) // abs(b)
if (a < 0) != (b < 0):
q = -q
r = a - b * q
return [a + b, a - b, a * b, q, r, a**n]
test_arith.py 29 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/do-integer-arithmetic/.
import pytest
from arith import arith
CASES = {
"small": (7, 2, 3, [9, 5, 14, 3, 1, 343]),
"exact-division": (20, 5, 2, [25, 15, 100, 4, 0, 400]),
"negative-dividend": (-7, 2, 3, [-5, -9, -14, -3, -1, -343]),
"negative-divisor": (7, -2, 2, [5, 9, -14, -3, 1, 49]),
"both-negative": (-7, -2, 1, [-9, -5, 14, 3, -1, -7]),
"zero-dividend": (0, 5, 0, [5, -5, 0, 0, 0, 1]),
"zero-power": (5, 3, 0, [8, 2, 15, 1, 2, 1]),
"divisor-larger": (3, 7, 1, [10, -4, 21, 0, 3, 3]),
"largest": (100000, 100000, 3, [200000, 0, 10000000000, 1, 0, 10**15]),
"smallest": (-100000, 1, 3, [-99999, -100001, -100000, -100000, 0, -(10**15)]),
}
@pytest.mark.parametrize("case", CASES)
def test_arith(case):
a, b, n, want = CASES[case]
assert arith(a, b, n) == want
def test_python_operators_floor():
assert (-7 // 2, -7 % 2) == (-4, 1)
assert divmod(-7, 2) == (-4, 1)
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-integer-arithmetic/.
#pragma once
#include <array>
#include <cstdint>
// arith returns a + b, a - b, a * b, a / b (rounded toward zero), a % b (with
// the sign of a) and a to the power n. b must not be 0. std::pow works on
// floating-point values, so a loop keeps the power exact.
constexpr std::array<std::int64_t, 6> arith(std::int64_t a, std::int64_t b, int n) {
std::int64_t power = 1;
for (int i = 0; i < n; i++) {
power *= a;
}
return {a + b, a - b, a * b, a / b, a % b, power};
}
test_arith.cpp 41 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-integer-arithmetic/.
#include "arith.hpp"
#include <cstdio>
namespace {
using Result = std::array<std::int64_t, 6>;
static_assert(arith(7, 2, 3) == Result{9, 5, 14, 3, 1, 343});
int failures = 0;
void check(const char *label, std::int64_t a, std::int64_t b, int n, const Result &want) {
if (arith(a, b, n) != want) {
std::fprintf(stderr, "case %s failed\n", label);
failures++;
}
}
} // namespace
int main() {
check("small", 7, 2, 3, {9, 5, 14, 3, 1, 343});
check("exact-division", 20, 5, 2, {25, 15, 100, 4, 0, 400});
check("negative-dividend", -7, 2, 3, {-5, -9, -14, -3, -1, -343});
check("negative-divisor", 7, -2, 2, {5, 9, -14, -3, 1, 49});
check("both-negative", -7, -2, 1, {-9, -5, 14, 3, -1, -7});
check("zero-dividend", 0, 5, 0, {5, -5, 0, 0, 0, 1});
check("zero-power", 5, 3, 0, {8, 2, 15, 1, 2, 1});
check("divisor-larger", 3, 7, 1, {10, -4, 21, 0, 3, 3});
check("largest", 100000, 100000, 3, {200000, 0, 10000000000, 1, 0, 1000000000000000});
check("smallest", -100000, 1, 3, {-99999, -100001, -100000, -100000, 0, -1000000000000000});
if (failures > 0) {
return 1;
}
std::printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-integer-arithmetic/.
final class Arith {
private Arith() {}
/**
* Returns the sum, the difference, the product, the quotient rounded toward zero, the remainder
* with the sign of a, and a to the power n.
*/
static long[] arith(long a, long b, int n) {
// Java has no power operator, and Math.pow works on double values. A loop keeps the power
// exact. ^ is not a power: it is the bitwise exclusive or.
long power = 1;
for (int i = 0; i < n; i++) {
power *= a;
}
return new long[] {a + b, a - b, a * b, a / b, a % b, power};
}
}
ArithTest.java 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-integer-arithmetic/.
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
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 ArithTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("small", 7L, 2L, 3, new long[] {9, 5, 14, 3, 1, 343}),
Arguments.of("exact-division", 20L, 5L, 2, new long[] {25, 15, 100, 4, 0, 400}),
Arguments.of("negative-dividend", -7L, 2L, 3, new long[] {-5, -9, -14, -3, -1, -343}),
Arguments.of("negative-divisor", 7L, -2L, 2, new long[] {5, 9, -14, -3, 1, 49}),
Arguments.of("both-negative", -7L, -2L, 1, new long[] {-9, -5, 14, 3, -1, -7}),
Arguments.of("zero-dividend", 0L, 5L, 0, new long[] {5, -5, 0, 0, 0, 1}),
Arguments.of("zero-power", 5L, 3L, 0, new long[] {8, 2, 15, 1, 2, 1}),
Arguments.of("divisor-larger", 3L, 7L, 1, new long[] {10, -4, 21, 0, 3, 3}),
Arguments.of(
"largest", 100000L, 100000L, 3,
new long[] {200000, 0, 10000000000L, 1, 0, 1000000000000000L}),
Arguments.of(
"smallest", -100000L, 1L, 3,
new long[] {-99999, -100001, -100000, -100000, 0, -1000000000000000L}));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void arith(String name, long a, long b, int n, long[] want) {
assertArrayEquals(want, Arith.arith(a, b, n), name);
}
@Test
void caretIsNotAPower() {
assertEquals(1, 2 ^ 3);
assertEquals(8.0, Math.pow(2, 3));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-integer-arithmetic/.
#include "arith.h"
void arith(int64_t a, int64_t b, int n, int64_t out[6]) {
// C has no power operator for integers. pow from <math.h> works on
// double values, so a loop keeps the power exact. ^ is the bitwise
// exclusive or.
int64_t power = 1;
for (int i = 0; i < n; i++) {
power *= a;
}
out[0] = a + b;
out[1] = a - b;
out[2] = a * b;
out[3] = a / b;
out[4] = a % b;
out[5] = power;
}
arith.h 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-integer-arithmetic/.
#ifndef ARITH_H
#define ARITH_H
#include <stdint.h>
// arith stores six results in out: a + b, a - b, a * b, a / b (rounded
// toward zero), a % b (with the sign of a) and a to the power n. b must not
// be 0.
void arith(int64_t a, int64_t b, int n, int64_t out[6]);
#endif
test_arith.c 40 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-integer-arithmetic/.
#include "arith.h"
#include <stdio.h>
static int failures = 0;
static void check(const char *label, int64_t a, int64_t b, int n, const int64_t want[6]) {
int64_t got[6];
arith(a, b, n, got);
for (int i = 0; i < 6; i++) {
if (got[i] != want[i]) {
fprintf(stderr, "case %s failed at %d\n", label, i);
failures++;
return;
}
}
}
#define CHECK(label, a, b, n, ...) check(label, a, b, n, (const int64_t[6]){__VA_ARGS__})
int main(void) {
CHECK("small", 7, 2, 3, 9, 5, 14, 3, 1, 343);
CHECK("exact-division", 20, 5, 2, 25, 15, 100, 4, 0, 400);
CHECK("negative-dividend", -7, 2, 3, -5, -9, -14, -3, -1, -343);
CHECK("negative-divisor", 7, -2, 2, 5, 9, -14, -3, 1, 49);
CHECK("both-negative", -7, -2, 1, -9, -5, 14, 3, -1, -7);
CHECK("zero-dividend", 0, 5, 0, 5, -5, 0, 0, 0, 1);
CHECK("zero-power", 5, 3, 0, 8, 2, 15, 1, 2, 1);
CHECK("divisor-larger", 3, 7, 1, 10, -4, 21, 0, 3, 3);
CHECK("largest", 100000, 100000, 3, 200000, 0, 10000000000, 1, 0, 1000000000000000);
CHECK("smallest", -100000, 1, 3, -99999, -100001, -100000, -100000, 0, -1000000000000000);
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-integer-arithmetic/.
public static class Arithmetic
{
// Returns a + b, a - b, a * b, a / b (rounded toward zero), a % b (with
// the sign of a) and a to the power n. C# has no power operator, and
// Math.Pow works on double values, so a loop keeps the power exact.
public static long[] Arith(long a, long b, int n)
{
long power = 1;
for (int i = 0; i < n; i++)
{
power *= a;
}
return new[] { a + b, a - b, a * b, a / b, a % b, power };
}
}
ArithTests.cs 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-integer-arithmetic/.
using System;
using Xunit;
public sealed class ArithTests
{
public static TheoryData<string, long, long, int, long[]> Cases => new()
{
{ "small", 7, 2, 3, new long[] { 9, 5, 14, 3, 1, 343 } },
{ "exact-division", 20, 5, 2, new long[] { 25, 15, 100, 4, 0, 400 } },
{ "negative-dividend", -7, 2, 3, new long[] { -5, -9, -14, -3, -1, -343 } },
{ "negative-divisor", 7, -2, 2, new long[] { 5, 9, -14, -3, 1, 49 } },
{ "both-negative", -7, -2, 1, new long[] { -9, -5, 14, 3, -1, -7 } },
{ "zero-dividend", 0, 5, 0, new long[] { 5, -5, 0, 0, 0, 1 } },
{ "zero-power", 5, 3, 0, new long[] { 8, 2, 15, 1, 2, 1 } },
{ "divisor-larger", 3, 7, 1, new long[] { 10, -4, 21, 0, 3, 3 } },
{ "largest", 100000, 100000, 3, new long[] { 200000, 0, 10000000000, 1, 0, 1000000000000000 } },
{ "smallest", -100000, 1, 3, new long[] { -99999, -100001, -100000, -100000, 0, -1000000000000000 } },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, long a, long b, int n, long[] want)
{
Assert.NotNull(name);
Assert.Equal(want, Arithmetic.Arith(a, b, n));
}
[Fact]
public void CaretIsNotAPower()
{
Assert.Equal(1, 2 ^ 3);
Assert.Equal(8.0, Math.Pow(2, 3));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-integer-arithmetic/.
// The values are numbers. A number is a 64-bit float, but the ranges of the
// contract keep each result below 2 ** 53, so each result is exact.
export function arith(a, b, n) {
// a / b is a float division; Math.trunc rounds the quotient toward zero.
// % is a remainder with the sign of the dividend.
return [a + b, a - b, a * b, Math.trunc(a / b), a % b, a ** n];
}
arith.test.js 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-integer-arithmetic/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { arith } from "./arith.js";
const cases = [
["small", 7, 2, 3, [9, 5, 14, 3, 1, 343]],
["exact-division", 20, 5, 2, [25, 15, 100, 4, 0, 400]],
["negative-dividend", -7, 2, 3, [-5, -9, -14, -3, -1, -343]],
["negative-divisor", 7, -2, 2, [5, 9, -14, -3, 1, 49]],
["both-negative", -7, -2, 1, [-9, -5, 14, 3, -1, -7]],
["zero-dividend", 0, 5, 0, [5, -5, 0, 0, 0, 1]],
["zero-power", 5, 3, 0, [8, 2, 15, 1, 2, 1]],
["divisor-larger", 3, 7, 1, [10, -4, 21, 0, 3, 3]],
["largest", 100000, 100000, 3, [200000, 0, 10000000000, 1, 0, 1e15]],
["smallest", -100000, 1, 3, [-99999, -100001, -100000, -100000, 0, -1e15]],
];
for (const [name, a, b, n, want] of cases) {
test(name, () => {
// deepEqual with Object.is would tell -0 from 0; compare with ===.
const got = arith(a, b, n);
assert.equal(got.length, want.length);
got.forEach((x, i) => assert.ok(x === want[i], `${name}[${i}]: ${x} != ${want[i]}`));
});
}
test("caret is not a power", () => {
assert.equal(2 ^ 3, 1);
assert.equal(2 ** 3, 8);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-integer-arithmetic/.
// The values are numbers. The ranges of the contract keep each result below
// 2 ** 53, so each result is exact.
export function arith(a: number, b: number, n: number): number[] {
// a / b is a float division; Math.trunc rounds the quotient toward zero.
return [a + b, a - b, a * b, Math.trunc(a / b), a % b, a ** n];
}
arith.test.ts 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-integer-arithmetic/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { arith } from "./arith.ts";
const cases: [string, number, number, number, number[]][] = [
["small", 7, 2, 3, [9, 5, 14, 3, 1, 343]],
["exact-division", 20, 5, 2, [25, 15, 100, 4, 0, 400]],
["negative-dividend", -7, 2, 3, [-5, -9, -14, -3, -1, -343]],
["negative-divisor", 7, -2, 2, [5, 9, -14, -3, 1, 49]],
["both-negative", -7, -2, 1, [-9, -5, 14, 3, -1, -7]],
["zero-dividend", 0, 5, 0, [5, -5, 0, 0, 0, 1]],
["zero-power", 5, 3, 0, [8, 2, 15, 1, 2, 1]],
["divisor-larger", 3, 7, 1, [10, -4, 21, 0, 3, 3]],
["largest", 100000, 100000, 3, [200000, 0, 10000000000, 1, 0, 1e15]],
["smallest", -100000, 1, 3, [-99999, -100001, -100000, -100000, 0, -1e15]],
];
for (const [name, a, b, n, want] of cases) {
test(name, () => {
const got = arith(a, b, n);
assert.equal(got.length, want.length);
got.forEach((x, i) => assert.ok(x === want[i], `${name}[${i}]: ${x} != ${want[i]}`));
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-integer-arithmetic/.
// Package arith applies the integer operations of Go.
package arith
// Arith returns a + b, a - b, a * b, a / b (rounded toward zero), a % b (with
// the sign of a) and a to the power n. b must not be 0.
func Arith(a, b int64, n int) [6]int64 {
// Go has no power operator, and math.Pow works on float64 values, so a
// loop keeps the power exact. ^ is the bitwise exclusive or.
power := int64(1)
for i := 0; i < n; i++ {
power *= a
}
return [6]int64{a + b, a - b, a * b, a / b, a % b, power}
}
arith_test.go 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-integer-arithmetic/.
package arith
import "testing"
var cases = []struct {
name string
a, b int64
n int
want [6]int64
}{
{"small", 7, 2, 3, [6]int64{9, 5, 14, 3, 1, 343}},
{"exact-division", 20, 5, 2, [6]int64{25, 15, 100, 4, 0, 400}},
{"negative-dividend", -7, 2, 3, [6]int64{-5, -9, -14, -3, -1, -343}},
{"negative-divisor", 7, -2, 2, [6]int64{5, 9, -14, -3, 1, 49}},
{"both-negative", -7, -2, 1, [6]int64{-9, -5, 14, 3, -1, -7}},
{"zero-dividend", 0, 5, 0, [6]int64{5, -5, 0, 0, 0, 1}},
{"zero-power", 5, 3, 0, [6]int64{8, 2, 15, 1, 2, 1}},
{"divisor-larger", 3, 7, 1, [6]int64{10, -4, 21, 0, 3, 3}},
{"largest", 100000, 100000, 3, [6]int64{200000, 0, 10000000000, 1, 0, 1000000000000000}},
{"smallest", -100000, 1, 3, [6]int64{-99999, -100001, -100000, -100000, 0, -1000000000000000}},
}
func TestArith(t *testing.T) {
for _, c := range cases {
if got := Arith(c.a, c.b, c.n); got != c.want {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
}
}
func TestCaretIsNotAPower(t *testing.T) {
if 2^3 != 1 {
t.Error("2 ^ 3 should be 1")
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-integer-arithmetic/.
/// Returns a + b, a - b, a * b, a / b (rounded toward zero), a % b (with the
/// sign of a) and a to the power n. b must not be 0.
pub fn arith(a: i64, b: i64, n: u32) -> [i64; 6] {
// i64::pow is an exact integer power. ^ is the bitwise exclusive or.
[a + b, a - b, a * b, a / b, a % b, a.pow(n)]
}
tests/arith_test.rs 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-integer-arithmetic/.
use algo_do_integer_arithmetic::arith;
#[test]
fn cases() {
let cases: Vec<(&str, i64, i64, u32, [i64; 6])> = vec![
("small", 7, 2, 3, [9, 5, 14, 3, 1, 343]),
("exact-division", 20, 5, 2, [25, 15, 100, 4, 0, 400]),
("negative-dividend", -7, 2, 3, [-5, -9, -14, -3, -1, -343]),
("negative-divisor", 7, -2, 2, [5, 9, -14, -3, 1, 49]),
("both-negative", -7, -2, 1, [-9, -5, 14, 3, -1, -7]),
("zero-dividend", 0, 5, 0, [5, -5, 0, 0, 0, 1]),
("zero-power", 5, 3, 0, [8, 2, 15, 1, 2, 1]),
("divisor-larger", 3, 7, 1, [10, -4, 21, 0, 3, 3]),
("largest", 100000, 100000, 3, [200000, 0, 10000000000, 1, 0, 1000000000000000]),
("smallest", -100000, 1, 3, [-99999, -100001, -100000, -100000, 0, -1000000000000000]),
];
for (name, a, b, n, want) in cases {
assert_eq!(arith(a, b, n), want, "case {name}");
}
}
#[test]
fn euclid_division_differs() {
assert_eq!((-7i64).div_euclid(2), -4);
assert_eq!((-7i64).rem_euclid(2), 1);
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/do-integer-arithmetic/.
# arith A B N
# Prints A + B, A - B, A * B, A / B (rounded toward zero), A % B (with the
# sign of A) and A to the power N, separated by spaces. B must not be 0.
# Bash arithmetic has the operator ** for a power; ^ is the bitwise
# exclusive or.
arith() {
local a=$1 b=$2 n=$3
echo "$((a + b)) $((a - b)) $((a * b)) $((a / b)) $((a % b)) $((a ** n))"
}
test_arith.bats 28 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/do-integer-arithmetic/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/arith.sh"
}
check() { # check WANT A B N
local want=$1 got
shift
got=$(arith "$@")
[ "$got" = "$want" ] || { printf 'got: %s\nwant: %s\n' "$got" "$want"; return 1; }
}
@test "small" { check "9 5 14 3 1 343" 7 2 3; }
@test "exact-division" { check "25 15 100 4 0 400" 20 5 2; }
@test "negative-dividend" { check "-5 -9 -14 -3 -1 -343" -7 2 3; }
@test "negative-divisor" { check "5 9 -14 -3 1 49" 7 -2 2; }
@test "both-negative" { check "-9 -5 14 3 -1 -7" -7 -2 1; }
@test "zero-dividend" { check "5 -5 0 0 0 1" 0 5 0; }
@test "zero-power" { check "8 2 15 1 2 1" 5 3 0; }
@test "divisor-larger" { check "10 -4 21 0 3 3" 3 7 1; }
@test "largest" { check "200000 0 10000000000 1 0 1000000000000000" 100000 100000 3; }
@test "smallest" { check "-99999 -100001 -100000 -100000 0 -1000000000000000" -100000 1 3; }
@test "caret is not a power" { [ "$((2 ^ 3))" = 1 ]; }
References
- Built-in Types, Python 3 documentation, Numeric Types, int, float, complex; Bitwise Operations on Integer Types
- Remainder (%), MDN Web Docs, the introduction
- Exponentiation (**), MDN Web Docs, the introduction
- The Java Language Specification, Java SE 27 Edition, Chapter 15: Expressions, 15.17.2 Division Operator /
- Math, Java SE 27 API, pow(double, double)
- Arithmetic operators, C reference, cppreference.com, Multiplicative operators
- pow, powf, powl, C reference, cppreference.com, the description
- Arithmetic operators, C# reference, Microsoft Learn, Division operator /, Integer division
- Math.Pow(Double, Double) Method, .NET API reference, Microsoft Learn, the definition
- The Go Programming Language Specification, Arithmetic operators; Integer operators
- math, Go standard library, func Pow
- Operator expressions, The Rust Reference, Arithmetic and Logical Binary Operators
- i64, Rust standard library, pow
- Bash Reference Manual, version 5.3, 6.5 Shell Arithmetic
- Number.isSafeInteger(), MDN Web Docs, Description
- Bitwise XOR (^), MDN Web Docs, the introduction
- BigInt, MDN Web Docs, Operators
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 QJYYVN Edit this page History Report an error Markdown