C++ ยท Chapter 13 of 49

C++ Math

The `<cmath>` header provides mathematical functions like `sqrt()`, `pow()`, `abs()`, `floor()` and `ceil()`. These work with doubles and floats for precise calculations.

For generating random numbers, modern C++ prefers `<random>` over the old `rand()` function, since it produces better-quality randomness.

Common functions

`sqrt(x)` returns the square root, `pow(x, y)` raises x to the power y, `abs(x)` returns the absolute value, and `max(a, b)`/`min(a, b)` from `<algorithm>` compare two values.

Rounding

`floor(x)` rounds down, `ceil(x)` rounds up, and `round(x)` rounds to the nearest integer โ€” all return a double.

Example 1 (cpp)
#include <cmath>
#include <iostream>
int main() {
    std::cout << sqrt(16) << " " << pow(2, 3);
}
Output
4 8

sqrt(16) is 4; pow(2,3) is 2 cubed = 8.

Example 2 (cpp)
#include <algorithm>
std::cout << std::max(3, 7);
Output
7

std::max returns the larger of two values.

Key points

  • <cmath> provides sqrt, pow, abs, floor, ceil.
  • <algorithm> provides std::max and std::min.
  • Prefer <random> over rand() for quality randomness.
  • Math functions typically operate on and return doubles.
๐Ÿ’ก Note: For competitive programming, memorise gcd(), lcm() (in <numeric> since C++17) to save time.

๐Ÿ“ Quick Quiz

1. Which header has sqrt() and pow()?

2. What does pow(2, 3) return?

3. Which header provides std::max?