Programming Search⌘K

Taskintro

Sum and multiply a list

Also called sum of a list, product of a list, sum and product of an array, sum(), math.prod, Iterator::sum, Iterator::product, Enumerable.Sum, std::accumulate, empty product.

Compute the sum and the product of a list of integers with a loop or a library function. The sum of an empty list is 0 and the product is 1, and a large product can overflow.

Task

Compute the sum and the product of a list of integers. The Rosetta Code task on the sum and product of an array says: "Compute the sum and product of an array of integers"1.

The function sum_and_product(items) returns the pair (sum, product). For example, sum_and_product([1, 2, 3, 4]) is (10, 24).

The sum of an empty list is 0, and the product of an empty list is 1. These are the identity values of addition and multiplication: adding 0 or multiplying by 1 does not change a number. With these start values, the sum and the product of a list are the same as the sum and the product of its parts.

The items are 64-bit signed integers, and each partial sum and each partial product fits in a 64-bit signed integer. A product grows fast: the product of 20 numbers of 9 is more than 10 to the power 19, which is out of range. The pitfalls show what happens then.

Solutions

Language Sum Product
Python sum(items) math.prod(items)
JavaScript, TypeScript items.reduce((a, x) => a + x, 0n) items.reduce((a, x) => a * x, 1n)
Java LongStream.of(items).sum() LongStream.of(items).reduce(1L, Math::multiplyExact)
C# items.Sum() items.Aggregate(1L, (a, x) => checked(a * x))
Go a for loop a for loop
Rust items.iter().sum::<i64>() items.iter().product::<i64>()
C a for loop a for loop
C++ std::accumulate(first, last, 0LL) std::accumulate(first, last, 1LL, std::multiplies<>())
Bash a for loop with $((sum + x)) a for loop with $((product * x))
  • Python. sum "Sums start and the items of an iterable from left to right and returns the total"2, and the start value is 0. math.prod is the product: "The default start value for the product is 1. When the iterable is empty, return the start value"3. Python integers have no size limit, so they do not overflow.
  • JavaScript. A number is a 64-bit float. Number.MAX_SAFE_INTEGER "represents the maximum safe integer in JavaScript (253 – 1)"4, that is, 2 to the power 53 minus 1, so the solution uses BigInt values. The start values 0n and 1n are BigInt values too, because a BigInt and a number cannot be mixed in + and *.
  • TypeScript. The same code as JavaScript, with the type bigint[].
  • Java. LongStream.sum wraps around on overflow with no error. Math.multiplyExact "Returns the product of the arguments, throwing an exception if the result overflows a long"5, so the product fails loudly. Math.addExact does the same for a sum.
  • C#. Enumerable.Sum of long values throws OverflowException when "The sum is larger than Int64.MaxValue"6. LINQ has no product function, so the solution uses Aggregate with a checked multiplication.
  • Go. There is no sum function for a slice, so the solution uses a loop. "For signed integers, the operations +, -, *, /, and << may legally overflow"7, with no error.
  • Rust. sum and product are methods of an iterator. product "Iterates over the entire iterator, multiplying all the elements. An empty iterator returns the one value of the type"8.
  • C. The solution uses a loop with long long values. A signed overflow in C is undefined behavior, so the precondition of the contract is important.
  • C++. std::accumulate with the start value 1 and std::multiplies gives the product9. The start values 0LL and 1LL make the accumulator a long long.
  • Bash. "Evaluation is done in the largest fixed-width integers available, with no check for overflow"10. The function prints the sum and the product on one line.

The Python functions:

import math

items = [1, 2, 3, 4]
print(sum(items), math.prod(items))
print(sum([]), math.prod([]))
print(sum(items, 100), math.prod(items, start=10))
print(math.prod(range(1, 26)))
Output
10 24
0 1
110 240
15511210043330985984000000

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • empty: the sum is 0 and the product is 1.
  • single: the sum and the product of one item are the item.
  • with-zero: one 0 makes the product 0.
  • two-negatives and three-negatives: the sign of the product depends on the count of negative items.
  • ones: a product of ones is 1.
  • large-product: 3037000499 squared is 9223372030926249001, near the largest 64-bit value 9223372036854775807.
  • to-the-limit: the sum is the largest 64-bit value.
  • beyond-double: 9007199254740993 is 2 to the power 53 plus 1. A 64-bit float cannot hold it, so a JavaScript number gives the wrong value.
  • min: the smallest 64-bit value, -9223372036854775808.

Pitfalls

  • A product overflows with no error. In Java, the long product of 2 to the power 32 and 2 to the power 32 is 0, because the result needs 65 bits. Math.multiplyExact throws an ArithmeticException instead:

This code runs but gives a wrong answer on purpose.

import java.util.stream.LongStream;

public class Main {
  public static void main(String[] args) {
    long[] items = {4294967296L, 4294967296L};
    System.out.println(LongStream.of(items).reduce(1L, (a, b) -> a * b));
    try {
      System.out.println(LongStream.of(items).reduce(1L, Math::multiplyExact));
    } catch (ArithmeticException e) {
      System.out.println(e.getClass().getSimpleName());
    }
  }
}
Output
0
ArithmeticException

In Rust, product "will panic if the computation overflows and overflow checks are enabled"8. A release build has no overflow checks by default, so the result wraps. checked_mul gives None in each build:

fn main() {
    let items: [i64; 2] = [1 << 32, 1 << 32];
    let product = items.iter().try_fold(1i64, |acc, &x| acc.checked_mul(x));
    println!("{product:?}");
    let wide: i128 = items.iter().map(|&x| i128::from(x)).product();
    println!("{wide}");
}
Output
None
18446744073709551616
  • A JavaScript number loses large integers. Above 2 to the power 53, a number cannot hold each integer, so a sum or a product gives a wrong result with no error. Use BigInt:

This code runs but gives a wrong answer on purpose.

console.log([9007199254740992, 1].reduce((a, x) => a + x, 0));
console.log([9007199254740992n, 1n].reduce((a, x) => a + x, 0n));
console.log([3037000499, 3037000499].reduce((a, x) => a * x, 1));
console.log([3037000499n, 3037000499n].reduce((a, x) => a * x, 1n));
Output
9007199254740992
9007199254740993n
9223372030926249000
9223372030926249001n
  • The sum of floats has a rounding error. 0.1 is not exact in binary, and each addition rounds the partial sum, so ten additions of 0.1 do not give 1.0. Compensated summation, such as the Kahan summation algorithm, "significantly reduces the numerical error in the total obtained by adding a sequence of finite-precision floating-point numbers, compared to the naive approach"11. In Python, math.fsum gives "an accurate floating-point sum of values in the iterable"3, and sum of floats uses an algorithm that "gives higher accuracy and better commutativity on most builds"2. A plain loop does not:
import math

items = [0.1] * 10
total = 0.0
for x in items:
    total += x
print(total)
print(sum(items), math.fsum(items))
Output
0.9999999999999999
1.0 1.0

JavaScript reduce adds from left to right, as the plain loop does:

const items = Array(10).fill(0.1);
console.log(items.reduce((a, x) => a + x, 0));
Output
0.9999999999999999

See Numerical pitfalls for the errors of floating-point sums.

  • The C++ start value sets the type. std::accumulate(v.begin(), v.end(), 0) adds double values into an int. See Reduce a list to a value for an example.

  • The product of an empty list. A product loop that starts at 0 always gives 0. Start the product at 1, and the sum at 0.

See Integer overflow or wraparound for what happens when a result does not fit, and Use big integers for integers with no size limit.

Code

The build runs the native tests of each language in a pinned toolchain.

sumprod.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/sum-and-multiply-a-list/.

import math


def sum_and_product(items: list[int]) -> tuple[int, int]:
    """Return the sum and the product of the items."""
    return sum(items), math.prod(items)


def sum_and_product_loop(items: list[int]) -> tuple[int, int]:
    """Return the same pair with a loop."""
    total, product = 0, 1
    for x in items:
        total += x
        product *= x
    return total, product
test_sumprod.py 27 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/sum-and-multiply-a-list/.

import pytest

from sumprod import sum_and_product, sum_and_product_loop

CASES = [
    ("small", [1, 2, 3, 4], (10, 24)),
    ("mixed", [3, -2, 5], (6, -30)),
    ("empty", [], (0, 1)),
    ("single", [7], (7, 7)),
    ("with-zero", [5, 0, 9], (14, 0)),
    ("two-negatives", [-2, -3], (-5, 6)),
    ("three-negatives", [-1, -2, -3], (-6, -6)),
    ("ones", [1, 1, 1], (3, 1)),
    ("large-product", [3037000499, 3037000499], (6074000998, 9223372030926249001)),
    ("to-the-limit", [9223372036854775806, 1], (9223372036854775807, 9223372036854775806)),
    ("beyond-double", [9007199254740993], (9007199254740993, 9007199254740993)),
    ("min", [-9223372036854775808], (-9223372036854775808, -9223372036854775808)),
]


@pytest.mark.parametrize(("name", "items", "want"), CASES, ids=[c[0] for c in CASES])
def test_sum_and_product(name, items, want):
    assert sum_and_product(items) == want
    assert sum_and_product_loop(items) == want
sumprod.hppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sum-and-multiply-a-list/.

#ifndef SUM_AND_PRODUCT_HPP
#define SUM_AND_PRODUCT_HPP

#include <functional>
#include <numeric>
#include <utility>
#include <vector>

// Returns the sum and the product of the items. The start values 0LL and
// 1LL set the type of the accumulator.
inline std::pair<long long, long long> sum_and_product(const std::vector<long long>& items) {
    return {std::accumulate(items.begin(), items.end(), 0LL),
            std::accumulate(items.begin(), items.end(), 1LL, std::multiplies<>())};
}

#endif
test_sumprod.cpp 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sum-and-multiply-a-list/.

#include <climits>
#include <cstdio>
#include <vector>

#include "sumprod.hpp"

namespace {

struct test_case {
    const char* name;
    std::vector<long long> items;
    long long sum, product;
};

const test_case cases[] = {
    {"small", {1, 2, 3, 4}, 10, 24},
    {"mixed", {3, -2, 5}, 6, -30},
    {"empty", {}, 0, 1},
    {"single", {7}, 7, 7},
    {"with-zero", {5, 0, 9}, 14, 0},
    {"two-negatives", {-2, -3}, -5, 6},
    {"three-negatives", {-1, -2, -3}, -6, -6},
    {"ones", {1, 1, 1}, 3, 1},
    {"large-product", {3037000499LL, 3037000499LL}, 6074000998LL, 9223372030926249001LL},
    {"to-the-limit", {9223372036854775806LL, 1}, 9223372036854775807LL, 9223372036854775806LL},
    {"beyond-double", {9007199254740993LL}, 9007199254740993LL, 9007199254740993LL},
    {"min", {LLONG_MIN}, LLONG_MIN, LLONG_MIN},
};

}  // namespace

int main() {
    int failures = 0;
    for (const auto& c : cases) {
        const auto [sum, product] = sum_and_product(c.items);
        if (sum != c.sum || product != c.product) {
            std::printf("FAIL %s: (%lld, %lld)\n", c.name, sum, product);
            ++failures;
        }
    }
    if (failures != 0) {
        return 1;
    }
    std::printf("ok\n");
    return 0;
}
SumProd.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sum-and-multiply-a-list/.

import java.util.stream.LongStream;

/** The sum and the product of a list of long values. */
public final class SumProd {
    private SumProd() {}

    /** Returns {sum, product}. multiplyExact and addExact throw on overflow. */
    public static long[] sumAndProduct(long[] items) {
        long sum = LongStream.of(items).reduce(0L, Math::addExact);
        long product = LongStream.of(items).reduce(1L, Math::multiplyExact);
        return new long[] {sum, product};
    }
}
SumProdTest.java 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sum-and-multiply-a-list/.

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

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 SumProdTest {
    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("small", new long[]{1, 2, 3, 4}, 10, 24),
                Arguments.of("mixed", new long[]{3, -2, 5}, 6, -30),
                Arguments.of("empty", new long[]{}, 0, 1),
                Arguments.of("single", new long[]{7}, 7, 7),
                Arguments.of("with-zero", new long[]{5, 0, 9}, 14, 0),
                Arguments.of("two-negatives", new long[]{-2, -3}, -5, 6),
                Arguments.of("three-negatives", new long[]{-1, -2, -3}, -6, -6),
                Arguments.of("ones", new long[]{1, 1, 1}, 3, 1),
                Arguments.of("large-product", new long[]{3037000499L, 3037000499L}, 6074000998L, 9223372030926249001L),
                Arguments.of("to-the-limit", new long[]{9223372036854775806L, 1}, 9223372036854775807L, 9223372036854775806L),
                Arguments.of("beyond-double", new long[]{9007199254740993L}, 9007199254740993L, 9007199254740993L),
                Arguments.of("min", new long[]{Long.MIN_VALUE}, Long.MIN_VALUE, Long.MIN_VALUE)
        );
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void sumAndProduct(String name, long[] items, long sum, long product) {
        assertArrayEquals(new long[] {sum, product}, SumProd.sumAndProduct(items));
    }

    @Test
    void overflowThrows() {
        assertThrows(ArithmeticException.class,
                () -> SumProd.sumAndProduct(new long[] {4294967296L, 4294967296L}));
    }
}
sumprod.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sum-and-multiply-a-list/.

#include "sumprod.h"

// A signed overflow in C is undefined behavior, so the caller must keep
// each partial result in range.
void sum_and_product(const long long *items, size_t n, long long *sum, long long *product) {
    long long s = 0;
    long long p = 1;
    for (size_t i = 0; i < n; i++) {
        s += items[i];
        p *= items[i];
    }
    *sum = s;
    *product = p;
}
sumprod.h 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sum-and-multiply-a-list/.

#ifndef SUM_AND_PRODUCT_H
#define SUM_AND_PRODUCT_H

#include <stddef.h>

// Sets *sum and *product to the sum and the product of the n items.
void sum_and_product(const long long *items, size_t n, long long *sum, long long *product);

#endif
test_sumprod.c 48 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sum-and-multiply-a-list/.

#include "sumprod.h"

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

struct test_case {
    const char *name;
    long long items[4];
    size_t n;
    long long sum, product;
};

static const struct test_case cases[] = {
    {"small", {1, 2, 3, 4}, 4, 10, 24},
    {"mixed", {3, -2, 5}, 3, 6, -30},
    {"empty", {0}, 0, 0, 1},
    {"single", {7}, 1, 7, 7},
    {"with-zero", {5, 0, 9}, 3, 14, 0},
    {"two-negatives", {-2, -3}, 2, -5, 6},
    {"three-negatives", {-1, -2, -3}, 3, -6, -6},
    {"ones", {1, 1, 1}, 3, 3, 1},
    {"large-product", {3037000499LL, 3037000499LL}, 2, 6074000998LL, 9223372030926249001LL},
    {"to-the-limit", {9223372036854775806LL, 1}, 2, 9223372036854775807LL, 9223372036854775806LL},
    {"beyond-double", {9007199254740993LL}, 1, 9007199254740993LL, 9007199254740993LL},
    {"min", {LLONG_MIN}, 1, LLONG_MIN, LLONG_MIN},
};

int main(void) {
    int failures = 0;
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *c = &cases[i];
        long long sum, product;
        sum_and_product(c->items, c->n, &sum, &product);
        if (sum != c->sum || product != c->product) {
            printf("FAIL %s: (%lld, %lld)\n", c->name, sum, product);
            failures++;
        }
    }
    if (failures != 0) {
        return EXIT_FAILURE;
    }
    printf("ok\n");
    return EXIT_SUCCESS;
}
SumProd.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sum-and-multiply-a-list/.

using System.Linq;

/// <summary>The sum and the product of a list of long values.</summary>
public static class SumProd
{
    /// <summary>Returns the sum and the product. Both throw OverflowException on overflow.</summary>
    public static (long Sum, long Product) SumAndProduct(long[] items)
    {
        long sum = items.Sum();
        long product = items.Aggregate(1L, (a, x) => checked(a * x));
        return (sum, product);
    }
}
SumProdTests.cs 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sum-and-multiply-a-list/.

using System;
using Xunit;

public sealed class SumProdTests
{
    public static TheoryData<string, long[], long, long> Cases => new()
    {
        { "small", new long[] { 1, 2, 3, 4 }, 10, 24 },
        { "mixed", new long[] { 3, -2, 5 }, 6, -30 },
        { "empty", Array.Empty<long>(), 0, 1 },
        { "single", new long[] { 7 }, 7, 7 },
        { "with-zero", new long[] { 5, 0, 9 }, 14, 0 },
        { "two-negatives", new long[] { -2, -3 }, -5, 6 },
        { "three-negatives", new long[] { -1, -2, -3 }, -6, -6 },
        { "ones", new long[] { 1, 1, 1 }, 3, 1 },
        { "large-product", new long[] { 3037000499, 3037000499 }, 6074000998, 9223372030926249001 },
        { "to-the-limit", new long[] { 9223372036854775806, 1 }, 9223372036854775807, 9223372036854775806 },
        { "beyond-double", new long[] { 9007199254740993 }, 9007199254740993, 9007199254740993 },
        { "min", new long[] { long.MinValue }, long.MinValue, long.MinValue },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void SumAndProduct(string name, long[] items, long sum, long product)
    {
        Assert.NotNull(name);
        Assert.Equal((sum, product), SumProd.SumAndProduct(items));
    }

    [Fact]
    public void OverflowThrows()
    {
        Assert.Throws<OverflowException>(() => SumProd.SumAndProduct([4294967296L, 4294967296L]));
    }
}
sumprod.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sum-and-multiply-a-list/.

/** Returns [sum, product] of a list of BigInt values. */
export function sumAndProduct(items) {
  const sum = items.reduce((a, x) => a + x, 0n);
  const product = items.reduce((a, x) => a * x, 1n);
  return [sum, product];
}
sumprod.test.js 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sum-and-multiply-a-list/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { sumAndProduct } from "./sumprod.js";

const cases = [
  ["small", [1n, 2n, 3n, 4n], [10n, 24n]],
  ["mixed", [3n, -2n, 5n], [6n, -30n]],
  ["empty", [], [0n, 1n]],
  ["single", [7n], [7n, 7n]],
  ["with-zero", [5n, 0n, 9n], [14n, 0n]],
  ["two-negatives", [-2n, -3n], [-5n, 6n]],
  ["three-negatives", [-1n, -2n, -3n], [-6n, -6n]],
  ["ones", [1n, 1n, 1n], [3n, 1n]],
  ["large-product", [3037000499n, 3037000499n], [6074000998n, 9223372030926249001n]],
  ["to-the-limit", [9223372036854775806n, 1n], [9223372036854775807n, 9223372036854775806n]],
  ["beyond-double", [9007199254740993n], [9007199254740993n, 9007199254740993n]],
  ["min", [-9223372036854775808n], [-9223372036854775808n, -9223372036854775808n]],
];

for (const [name, items, want] of cases) {
  test(name, () => {
    assert.deepEqual(sumAndProduct(items), want);
  });
}
sumprod.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sum-and-multiply-a-list/.

/** Returns [sum, product] of a list of bigint values. */
export function sumAndProduct(items: bigint[]): [bigint, bigint] {
  const sum = items.reduce((a, x) => a + x, 0n);
  const product = items.reduce((a, x) => a * x, 1n);
  return [sum, product];
}
sumprod.test.ts 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sum-and-multiply-a-list/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { sumAndProduct } from "./sumprod.ts";

const cases: [string, bigint[], [bigint, bigint]][] = [
  ["small", [1n, 2n, 3n, 4n], [10n, 24n]],
  ["mixed", [3n, -2n, 5n], [6n, -30n]],
  ["empty", [], [0n, 1n]],
  ["single", [7n], [7n, 7n]],
  ["with-zero", [5n, 0n, 9n], [14n, 0n]],
  ["two-negatives", [-2n, -3n], [-5n, 6n]],
  ["three-negatives", [-1n, -2n, -3n], [-6n, -6n]],
  ["ones", [1n, 1n, 1n], [3n, 1n]],
  ["large-product", [3037000499n, 3037000499n], [6074000998n, 9223372030926249001n]],
  ["to-the-limit", [9223372036854775806n, 1n], [9223372036854775807n, 9223372036854775806n]],
  ["beyond-double", [9007199254740993n], [9007199254740993n, 9007199254740993n]],
  ["min", [-9223372036854775808n], [-9223372036854775808n, -9223372036854775808n]],
];

for (const [name, items, want] of cases) {
  test(name, () => {
    assert.deepEqual(sumAndProduct(items), want);
  });
}
sumprod.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sum-and-multiply-a-list/.

// Package sumprod computes the sum and the product of a slice of integers.
package sumprod

// SumAndProduct returns the sum and the product of the items. Go has no
// sum function for a slice, and the operations wrap around on overflow.
func SumAndProduct(items []int64) (sum, product int64) {
	product = 1
	for _, x := range items {
		sum += x
		product *= x
	}
	return sum, product
}
sumprod_test.go 48 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sum-and-multiply-a-list/.

package sumprod

import (
	"math"
	"testing"
)

var cases = []struct {
	name         string
	items        []int64
	sum, product int64
}{
	{"small", []int64{1, 2, 3, 4}, 10, 24},
	{"mixed", []int64{3, -2, 5}, 6, -30},
	{"empty", []int64{}, 0, 1},
	{"single", []int64{7}, 7, 7},
	{"with-zero", []int64{5, 0, 9}, 14, 0},
	{"two-negatives", []int64{-2, -3}, -5, 6},
	{"three-negatives", []int64{-1, -2, -3}, -6, -6},
	{"ones", []int64{1, 1, 1}, 3, 1},
	{"large-product", []int64{3037000499, 3037000499}, 6074000998, 9223372030926249001},
	{"to-the-limit", []int64{9223372036854775806, 1}, 9223372036854775807, 9223372036854775806},
	{"beyond-double", []int64{9007199254740993}, 9007199254740993, 9007199254740993},
	{"min", []int64{math.MinInt64}, math.MinInt64, math.MinInt64},
}

func TestSumAndProduct(t *testing.T) {
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			sum, product := SumAndProduct(c.items)
			if sum != c.sum || product != c.product {
				t.Fatalf("got (%d, %d), want (%d, %d)", sum, product, c.sum, c.product)
			}
		})
	}
}

func TestWrapAround(t *testing.T) {
	if _, product := SumAndProduct([]int64{1 << 32, 1 << 32}); product != 0 {
		t.Fatalf("got %d, want 0", product)
	}
	if sum, _ := SumAndProduct([]int64{math.MaxInt64, 1}); sum != math.MinInt64 {
		t.Fatalf("got %d", sum)
	}
}
sumprod.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sum-and-multiply-a-list/.

/// Returns the sum and the product of the items. With overflow checks on,
/// sum and product panic on overflow.
pub fn sum_and_product(items: &[i64]) -> (i64, i64) {
    (items.iter().sum(), items.iter().product())
}

/// Returns None if a partial sum or product overflows.
pub fn checked_sum_and_product(items: &[i64]) -> Option<(i64, i64)> {
    let sum = items.iter().try_fold(0i64, |a, &x| a.checked_add(x))?;
    let product = items.iter().try_fold(1i64, |a, &x| a.checked_mul(x))?;
    Some((sum, product))
}
tests/sumprod_test.rs 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sum-and-multiply-a-list/.

use algo_sum_and_multiply_a_list::{checked_sum_and_product, sum_and_product};

const CASES: &[(&str, &[i64], (i64, i64))] = &[
    ("small", &[1, 2, 3, 4], (10, 24)),
    ("mixed", &[3, -2, 5], (6, -30)),
    ("empty", &[], (0, 1)),
    ("single", &[7], (7, 7)),
    ("with-zero", &[5, 0, 9], (14, 0)),
    ("two-negatives", &[-2, -3], (-5, 6)),
    ("three-negatives", &[-1, -2, -3], (-6, -6)),
    ("ones", &[1, 1, 1], (3, 1)),
    ("large-product", &[3037000499, 3037000499], (6074000998, 9223372030926249001)),
    ("to-the-limit", &[9223372036854775806, 1], (9223372036854775807, 9223372036854775806)),
    ("beyond-double", &[9007199254740993], (9007199254740993, 9007199254740993)),
    ("min", &[i64::MIN], (i64::MIN, i64::MIN)),
];

#[test]
fn cases() {
    for &(name, items, want) in CASES {
        assert_eq!(sum_and_product(items), want, "{name}");
        assert_eq!(checked_sum_and_product(items), Some(want), "{name}");
    }
}

#[test]
fn overflow_is_none() {
    assert_eq!(checked_sum_and_product(&[1 << 32, 1 << 32]), None);
}
sumprod.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/sum-and-multiply-a-list/.

# sum_and_product ITEM...
# Prints "sum product". Bash arithmetic uses 64-bit integers with no check
# for overflow.
sum_and_product() {
  local sum=0 product=1 x
  for x in "$@"; do
    sum=$((sum + x))
    product=$((product * x))
  done
  printf '%s %s\n' "$sum" "$product"
}
test_sumprod.bats 22 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/sum-and-multiply-a-list/.

setup() {
  source "$BATS_TEST_DIRNAME/sumprod.sh"
}

@test "small" { run sum_and_product 1 2 3 4; [ "$output" = "10 24" ]; }
@test "mixed" { run sum_and_product 3 -2 5; [ "$output" = "6 -30" ]; }
@test "empty" { run sum_and_product ; [ "$output" = "0 1" ]; }
@test "single" { run sum_and_product 7; [ "$output" = "7 7" ]; }
@test "with-zero" { run sum_and_product 5 0 9; [ "$output" = "14 0" ]; }
@test "two-negatives" { run sum_and_product -2 -3; [ "$output" = "-5 6" ]; }
@test "three-negatives" { run sum_and_product -1 -2 -3; [ "$output" = "-6 -6" ]; }
@test "ones" { run sum_and_product 1 1 1; [ "$output" = "3 1" ]; }
@test "large-product" { run sum_and_product 3037000499 3037000499; [ "$output" = "6074000998 9223372030926249001" ]; }
@test "to-the-limit" { run sum_and_product 9223372036854775806 1; [ "$output" = "9223372036854775807 9223372036854775806" ]; }
@test "beyond-double" { run sum_and_product 9007199254740993; [ "$output" = "9007199254740993 9007199254740993" ]; }
@test "min" { run sum_and_product -9223372036854775808; [ "$output" = "-9223372036854775808 -9223372036854775808" ]; }

@test "wraps-around" { run sum_and_product 4294967296 4294967296; [ "$output" = "8589934592 0" ]; }

References

  1. Rosetta Code, Sum and product of an array (task text, from acmeism/RosettaCodeData), task text
  2. The Python Standard Library, Built-in Functions, sum()
  3. The Python Standard Library, math, math.prod; math.fsum
  4. MDN Web Docs, Number.MAX_SAFE_INTEGER, the introduction
  5. Java SE 25 API, Class Math, multiplyExact(long, long)
  6. .NET API reference, Enumerable.Sum method, Sum(IEnumerable<Int64>), Exceptions
  7. The Go Programming Language Specification, Integer overflow
  8. Rust standard library, trait Iterator, sum; product
  9. cppreference.com, std::accumulate, Example
  10. Bash Reference Manual, 6.5 Shell Arithmetic
  11. Wikipedia, Kahan summation algorithm, the introduction

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source