Loading lessons...
Remainder and Exponentiation
Remainder and Exponentiation
Two special math tools: the remainder operator % and the power function pow().
The remainder operator
% gives what is left over after a division. 7 % 3 is 1: three goes into seven two whole times, and 1 is left.
cout << 7 % 2 << endl; // 1
cout << 7 % 3 << endl; // 2
cout << 12 % 6 << endl; // 0
A great trick: checking even numbers
x % 2 == 0 is true exactly when x is even. That is one of the most used patterns in C++.
int x = 8;
bool isEven = (x % 2 == 0); // true
Division team: quotient and remainder
10 / 4 is the quotient (2) and 10 % 4 is the remainder (2). Together they cover everything a division leaves behind.
Exponentiation with pow
C++ has no power symbol. 2 ^ 3 means something else in C++! For powers, use pow(base, exponent) from the <cmath> header:
#include <cmath>
using namespace std;
cout << pow(2, 4) << endl; // 16
cout << pow(3, 2) << endl; // 9
Inside pow(x, y), the first number is the base and the second is the exponent, so pow(2, 4) means 2 2 2 * 2. pow returns a double, so the result can have decimals.
TL;DR
%gives the remainder of a division.- Check even numbers with
x % 2 == 0. - Do not use
^for powers in C++. - Use
pow(base, exponent)from<cmath>for exponents.