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.
import math x1, y1, x2, y2 = map(int, input().split()) dx = abs(x2 - x1) # 3dy = abs(y2 - y1) # 1 - 7 = -6 → 6print(dx, dy) d2 = dx ** 2 + dy ** 2 # 45, 정수끼리라 정수 그대로dist = math.sqrt(d2) # 6.708203932499369print(f"{dist:.2f}") # 정수 제곱근: r * r <= d2인 가장 큰 정수r = int(dist)while r * r > d2: r -= 1while (r + 1) * (r + 1) <= d2: r += 1print(r) # math.isqrt(d2)도 같은 답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);import { readFileSync } from "node:fs";const [x1, y1, x2, y2]: number[] = readFileSync(0, "utf8").trim().split(" ").map(Number); const dx: number = Math.abs(x2 - x1); // 3const dy: number = Math.abs(y2 - y1); // 1 - 7 = -6 → 6console.log(dx, dy); const d2: number = dx ** 2 + dy ** 2; // 45const dist: number = Math.sqrt(d2); // 6.708203932499369console.log(dist.toFixed(2)); // 정수 제곱근: r * r <= d2인 가장 큰 정수let r: number = Math.floor(dist);while (r * r > d2) r--;while ((r + 1) * (r + 1) <= d2) r++;console.log(r);import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int x1 = in.nextInt(), y1 = in.nextInt(), x2 = in.nextInt(), y2 = in.nextInt(); int dx = Math.abs(x2 - x1); // 3 int dy = Math.abs(y2 - y1); // 1 - 7 = -6 → 6 System.out.println(dx + " " + dy); int d2 = (int) (Math.pow(dx, 2) + Math.pow(dy, 2)); // pow는 double을 돌려줘요 double dist = Math.sqrt(d2); // 6.708203932499369 System.out.println(String.format("%.2f", dist)); // 정수 제곱근: r * r <= d2인 가장 큰 정수 int r = (int) dist; while (r * r > d2) r--; while ((r + 1) * (r + 1) <= d2) r++; System.out.println(r); }}using System; class Program{ static void Main() { string[] p = Console.ReadLine().Split(' '); int x1 = int.Parse(p[0]), y1 = int.Parse(p[1]), x2 = int.Parse(p[2]), y2 = int.Parse(p[3]); int dx = Math.Abs(x2 - x1); // 3 int dy = Math.Abs(y2 - y1); // 1 - 7 = -6 → 6 Console.WriteLine($"{dx} {dy}"); int d2 = (int)(Math.Pow(dx, 2) + Math.Pow(dy, 2)); // Pow는 double을 돌려줘요 double dist = Math.Sqrt(d2); // 6.708203932499369 Console.WriteLine(dist.ToString("F2")); // 정수 제곱근: r * r <= d2인 가장 큰 정수 int r = (int)dist; while (r * r > d2) r--; while ((r + 1) * (r + 1) <= d2) r++; Console.WriteLine(r); }}#include <cmath>#include <iomanip>#include <iostream> int main() { int x1, y1, x2, y2; std::cin >> x1 >> y1 >> x2 >> y2; int dx = std::abs(x2 - x1); // 3 int dy = std::abs(y2 - y1); // 1 - 7 = -6 → 6 std::cout << dx << ' ' << dy << '\n'; int d2 = (int)(std::pow(dx, 2) + std::pow(dy, 2)); // pow는 double을 돌려줘요 double dist = std::sqrt(d2); // 6.708203932499369 std::cout << std::fixed << std::setprecision(2) << dist << '\n'; // 정수 제곱근: r * r <= d2인 가장 큰 정수 int r = (int)dist; while (r * r > d2) r--; while ((r + 1) * (r + 1) <= d2) r++; std::cout << r << '\n';}#include <stdio.h>#include <stdlib.h>#include <math.h> int main(void) { int x1, y1, x2, y2; scanf("%d %d %d %d", &x1, &y1, &x2, &y2); int dx = abs(x2 - x1); /* 3 — abs는 정수용, 실수는 fabs */ int dy = abs(y2 - y1); /* 1 - 7 = -6 → 6 */ printf("%d %d\n", dx, dy); int d2 = (int)(pow(dx, 2) + pow(dy, 2)); /* pow는 double을 돌려줘요 */ double dist = sqrt(d2); /* 6.708203932499369 */ printf("%.2f\n", dist); /* 정수 제곱근: r * r <= d2인 가장 큰 정수 */ int r = (int)dist; while (r * r > d2) r--; while ((r + 1) * (r + 1) <= d2) r++; printf("%d\n", r); return 0;}p = Console.ReadNumbers();x1 = p[0];y1 = p[1];x2 = p[2];y2 = p[3]; dx = Mathf.Abs(x2 - x1); // 3dy = Mathf.Abs(y2 - y1); // 1 - 7 = -6 → 6Console.WriteLine(dx + " " + dy); d2 = dx * dx + dy * dy; // 거듭제곱 함수가 없어서 곱해요dist = Mathf.Sqrt(d2); // 6.708203932Console.WriteLine(Str.Fixed(dist, 2)); // 정수 제곱근: r * r <= d2인 가장 큰 정수r = Mathf.Floor(dist);while (r * r > d2){ r--;}while ((r + 1) * (r + 1) <= d2){ r++;}Console.WriteLine(r);2 7 5 1
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 - 7is -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 apowfunction.^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's2 ** 10is the integer1024.powin 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 * xstays an integer and is simpler. - A square root is the value whose square is the number.
sqrtalways returns a floating-point number.
The square root of 45 is6.708203932499369, and even the exact 25 prints as5.0in Python and Java. - The integer square root is the largest integer
rwithr * r <= n.
Drop the decimals of thesqrtresult, then multiply back and adjust.
The twowhilelines in the example are that check. - The square root of a negative number does not come out as a number.
Python stops with aValueError; the other languages returnNaN(not a number) and carry on.
How each language writes it
| Python | abs(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 |
|---|---|
| JavaScript | Math.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 |
| TypeScript | Same as JavaScript. Every result is a number |
| Java | Math.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 |
| C | abs(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 |
| Craykon | Mathf.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
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 ^ 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.
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.
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.