Math

Updated: 2018-06-11

Sum of Array

Javascript

Use .reduce():

> a = [1, 2, 3, 4]
[ 1, 2, 3, 4 ]
> a.reduce((x, y) => x + y)
10

The full signature is:

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

However only total and currentValue are required.

Max/Min/Mean

Hack

Math\max()
Math\min()
Math\mean()

Round

Java

Integer.valueOf(Math.round(value));

Log

Java

These 2 are equivalent:

Math.log1p(x)
Math.log(x+1)

Mod

  • C++/Java: if you directly calculate -4 % 3 you will get -1. You can use function: a % b = (a % b + b) % b to make it is a non negative integer.
  • Python: you can directly use -1 % 3, you will get 2 automatically.