{ }codelper

Learn › JavaScript

Going further · 23

Absolute value, powers, square roots

Dropping the sign, multiplying many times, and finding the value whose square is a number.

These are the three calculations you need most often after the four basic operations.
The example below reads the coordinates of two points, prints how many cells apart they are across and down, prints the distance between them to two decimal places, and prints the largest whole number that does not exceed that distance.

const [x1, y1, x2, y2] = require("fs").readFileSync(0, "utf8").trim().split(" ").map(Number); const dx = Math.abs(x2 - x1); // 3const dy = Math.abs(y2 - y1); // 1 - 7 = -6 → 6console.log(dx, dy); const d2 = dx ** 2 + dy ** 2; // 45const dist = Math.sqrt(d2); // 6.708203932499369console.log(dist.toFixed(2)); // 정수 제곱근: r * r <= d2인 가장 큰 정수let r = Math.floor(dist);while (r * r > d2) r--;while ((r + 1) * (r + 1) <= d2) r++;console.log(r);
stdin
2 7 5 1
stdout
3 6
6.71
6

Key points

  • The absolute value is the size of a number without its sign.
    Use it to find how far apart two values are: abs(a - b) works without knowing which one is larger.
    1 - 7 is -6, but the points are 6 cells apart.
  • A power multiplies the same number several times.
    Python and JavaScript have the ** operator; the other languages use a pow function.
    ^ is not a power in any of these languages.
  • Whether a power comes out as an integer or a floating-point number depends on the language.
    Python's 2 ** 10 is the integer 1024.
    pow in Java, C#, C and C++ returns a floating-point number (double) even for integers, so it must be converted before it goes into an integer variable.
    For a square, x * x stays an integer and is simpler.
  • A square root is the value whose square is the number.
    sqrt always returns a floating-point number.
    The square root of 45 is 6.708203932499369, and even the exact 25 prints as 5.0 in Python and Java.
  • The integer square root is the largest integer r with r * r <= n.
    Drop the decimals of the sqrt result, then multiply back and adjust.
    The two while lines in the example are that check.
  • The square root of a negative number does not come out as a number.
    Python stops with a ValueError; the other languages return NaN (not a number) and carry on.

How each language writes it

Pythonabs(x), x ** 2, math.sqrt(x) (import math).
math.isqrt(n) gives the integer square root directly.
2 64 is still an exact integer, and 2 -1 is 0.5.
-2 2 is -4, so write (-2) 2
JavaScriptMath.abs(x), x ** 2 (or Math.pow(x, 2)), Math.sqrt(x); drop decimals with Math.floor(...).
-2 2 is a SyntaxError, so write (-2) 2
TypeScriptSame as JavaScript.
Every result is a number
JavaMath.abs(x), Math.pow(x, 2), Math.sqrt(x).
Math.pow(2, 10) is 1024.0.
int p = Math.pow(2, 10); is a compile error, so convert with (int) Math.pow(2, 10)
C#Math.Abs(x), Math.Pow(x, 2), Math.Sqrt(x).
Math.Pow is a double, so int p = Math.Pow(2, 10); is error CS0266.
Convert with (int)Math.Pow(2, 10)
C++std::abs(x), std::pow(x, 2), std::sqrt(x) from <cmath>.
std::pow is a double, so std::cout << std::pow(10, 6) prints 1e+06.
Convert with (long long) to print an integer
Cabs(x) from <stdlib.h> for integers, fabs(x) from <math.h> for floating-point numbers.
pow(x, 2) and sqrt(x) are in <math.h> too and return a double
CraykonMathf.Abs(x), Mathf.Sqrt(x); drop decimals with Mathf.Floor(...).
There is no power operator or function, so multiply: x * x.
2 ^ 10 and 2 ** 10 are compile errors

Common mistakes

Using ^ for a powerPython · JavaScript · TypeScript · Java · C# · C · C++

System.out.println(2 ^ 10);

→ 8 — not 1024. ^ is a different operation that compares the bits of the two numbers (XOR). There is no error, just an unexpected number

Use 2 ** 10 in Python and JavaScript and the pow function elsewhere (in Java, (int) Math.pow(2, 10)).
Craykon reports ^ as a compile error.

Trusting the floored sqrt as the integer square root

const x = 9007199136250224; // 94906265 * 94906265 - 1
console.log(Math.floor(Math.sqrt(x)));

→ 94906265 — but the square of 94906265 is 1 more than x. The right answer is 94906264. For large numbers the result of sqrt is rounded and lands exactly on 94906265. All 8 languages give the same value

Floor it, then check by multiplying: adding while (r * r > x) r--; gives 94906264.
In Python, math.isqrt(x) gives the exact answer.

Using the integer abs on a floating-point numberC · C++

double d = -2.7;
printf("%d\n", abs(d));

→ 2 — not 2.7. abs from <stdlib.h> is for integers, so the decimals are dropped first. In C++ too, abs(d) written without std:: gave 2

Use fabs(d) in C and std::abs(d) in C++.
Both give 2.7.

How languages differ
When the answer has to be an integer, stay inside integers as far as you can.
To ask whether a distance is at most r, do not use sqrt; compare the squares, as in dx * dx + dy * dy <= r * r, and no floating-point number gets involved.
Use sqrt only when you really need the root, and after converting to an integer, multiply once to check.
Powers are the same.
pow works in floating point, so for very large numbers the last digits come out wrong: 3 multiplied 34 times is 16677181699666569, but (long) Math.pow(3, 34) in Java gives 16677181699666568.
When you need a large integer power in Java, C#, C or C++, multiply step by step into a long (long long) variable.

Practice