# 5.3 — Modulus and Exponentiation

The modulus operator

The modulus operator (also informally known as the remainder operator) is an operator that returns the remainder after doing an integer division. For example, 7 / 4 = 1 remainder 3. Therefore, 7 % 4 = 3. As another example, 25 / 7 = 3 remainder 4, thus 25 % 7 = 4. Modulus only works with integer operands.

Modulus is most useful for testing whether a number is evenly divisible by another number: if x % y evaluates to 0, then we know that x is evenly divisible by y.

Here are a couple runs of this program:

```Enter an integer: 6
Enter another integer: 3
The remainder is: 0
6 is evenly divisible by 3
```
```Enter an integer: 6
Enter another integer: 4
The remainder is: 2
6 is not evenly divisible by 4
```

Modulus with negative numbers

The modulus operator can also work with negative operands. `x % y` always returns results with the sign of x.

Running the above program:

```Enter an integer: -6
Enter another integer: 4
The remainder is: -2
-6 is not evenly divisible by 4
```
```Enter an integer: 6
Enter another integer: -4
The remainder is: 2
6 is not evenly divisible by -4
```

In both cases, you can see the remainder takes the sign of the first operand.

Warning

Prior to C++11, modulus with a negative operand could result in either a positive or negative result. This was made predictable in C++11.

Where’s the exponent operator?

You’ll note that the ^ operator (commonly used to denote exponentiation in mathematics) is a Bitwise XOR operation in C++ (covered in lesson O.3 -- Bit manipulation with bitwise operators and bit masks). C++ does not include an exponent operator.

To do exponents in C++, #include the <cmath> header, and use the pow() function:

Note that the parameters (and return value) of function pow() are of type double. Due to rounding errors in floating point numbers, the results of pow() may not be precise (even if you pass it integers or whole numbers).

If you want to do integer exponentiation, you’re best off using your own function to do so. The following function implements integer exponentiation (using the non-intuitive “exponentiation by squaring” algorithm for efficiency):

Don’t worry if you don’t understand how this function works -- you don’t need to understand it in order to call it.

Produces:

```13841287201
```

Warning

In the vast majority of cases, integer exponentiation will overflow the integral type. This is likely why such a function wasn’t included in the standard library in the first place.

Quiz time

Question #1

What does the following expression evaluate to? `6 + 5 * 4 % 3`

Show Solution

Question #2

Write a program that asks the user to input an integer, and tells the user whether the number is even or odd. Write a function called isEven() that returns true if an integer passed to it is even, and false otherwise. Use the modulus operator to test whether the integer parameter is even.

Hint: You’ll need to use if statements and the comparison operator (==) for this program. See lesson 4.9 -- Boolean values if you need a refresher on how to do this.

Your program should match the following output:

```Enter an integer: 5
5 is odd
```

Show Solution 5.4 -- Increment/decrement operators, and side effects Index 5.2 -- Arithmetic operators

### 85 comments to 5.3 — Modulus and Exponentiation

• Waldo Lemmer

Great tutorial once again :)

I've noticed that you always initialize a variable, even if gets assigned a value in the next statement:

I always do it this way:

but I would like to have my mind changed :)

1. Is my way of doing it faster than your way?
2. If the input is invalid, x becomes 0 (C++11 and up). x is therefore never uninitialized (after line 2), and can therefore not cause undefined behavior. Why initialize it in the first place then?

Sorry about my English being all over the place in this comment, English isn't my native language and I'm tired :)

• nascardriver

1. Yes
2. If you always initialize everything, you'll never have problems with uninitialized variables. If you know what you're doing, you can skip initialization. Though, learncpp is targeted at beginners, who usually don't know what they're doing and would have a hard time debugging uninitialized variables.

• Waldo Lemmer

Thank you. I will only leave variables uninitialised when I'm confident that it's safe (like when using std::cin afterwards).

• yeokaiwei

For Question 2, int won't work for extremely large numbers like 423509285165835268358. However, humans can intuitively check the last digit. Would it be better if we take the last digit before the decimal point and see if it is even or odd?

In the Qn 2 example, if I input 423509285165835268358 or any large even number, it will return "2147483647 is odd".

• nascardriver

`std::cin` clamps input that don't fit into the targeted type. To handle infinitely large numbers, you'd have to write a custom type.
If you just want to check if the number is odd or even, your idea of looking at the last digit suffices.
Not everything required to do this has been taught yet, but telling by your previous posts, you know more than what's been taught up to this point. Give it a try if you like to.

• Akbar

Instead of making a function that returns a boolean value, why don't you insert the boolean value to the if statement?

• Sheepy69

This is my take on even/odd exercise.

I also have a question regarding your boolean function.  Can you please explain to me what exactly it does? From what I know, it act/behave the same as an integer/float function which return a value? In this cause, would it make more sense to use an integer function to return an integer value?

• nascardriver

`isEven` only has 2 possible outcomes. Either the value is even, or it's odd. That's what booleans are there for, they're either `true` or `false`. Using an integer for this would be very confusing, because the user of the function would have to read the definition or documentation to figure out what each value means.

• sheepy69

So, you're saying that Boolean function is only good for if there's 2 possible outcome? What are some other way we can use boolean function as, aside from returning true or flase?

Sorry for many question.

• nascardriver

"Boolean function" only means "a function returning a bool". There's no other meaning to it.

• Sheepy69

May I ask why you use int_fast# in this case? If it value 1, would it make sense to rather use something like int_least8_t? this will minimum memory and number range.
or maybe I fail to understand the whole code (function) you wrote with it.

• nascardriver

`result` can have a very large value. 1 is only the initial value.

• Ngomez

Instead of using the % operator I would like to be able to read the first bit of a variable
If the first bit of the variable is 1, the value will be odd if it is 0 it will be pair.

Example:
00000111 = 7 odd
00001101 = 13 odd
00000100 = 4 pair
10000000 = 128 pair
00000001 = 1 odd
00000010 = 2 pair

Could someone help me with the code, I don't know how to make it

• nascardriver

• evolve

will this code work same?

• John

Here's another interesting way to solve the question by exploiting the fact that division of integers drops the fractional part.

• McKeon

You were right about how i was tempted to write the code shown in Question #2.

Thats been my main concern about this whole learning experience is that i know how to utilize what ive learned and get it to work, but learning other ways to do it that are either more effecient and or "more or less complex", Are my main concern.

I need to get better at the problem solving of things and the logic of the writing the programs. I'm sure i will get better as i go but do you have a tip for me to learn better ways for me to learn how to better problem solve about how i need to setup what im about to write. its hard for me to word but i think you know what i am trying to say.

It's just like how when you learn math in school you are like i will never use this but you dont realize you actually will use it all the time because it improves your problem solving skills and the way you think about things it rewires your brain. That is what i want to get better at is coming up with better ways. maybe i just answered my own question.

But how you had shown "you may have been tempted to write it this way" and i did and sure it worked. But then you shown "well you can do this instead you dont have to itterate so much and there is an easier way to do this" thats what inspires me with coding and what i find rewarding is when i can do these little excercises and they look exactly like your solution and show me another better way i could have done it.

• Andreas Krug

Hello Alex & nascardriver,

in chapter 2.11 - Header files (The #include order of header files) you wrote to sort the headers alphabetically, but the third code example from (Where’s the exponent operator?) in this chapter has iostream before cstdint.

Keep up the great work,
Andreas

• It's+Me

#include<iostream>
bool IsEven(int x) {

if (x % 2 == 0) {
std::cout << x <<" is even to ";
}
else {
std::cout << x << " is odd to ";
}
return false;
}
int main() {
std::cout << "Enter an integer: ";
int x;
std::cin >> x;
std::cout << IsEven(x);

}

// not so perfect as your program though :(

• Amir

hope this is okay

• Anders Nesse

Hi Amir.

My problem with this function is that it's not intuitive for other users. The function name is "isEven", but returns 0 (false) if the number is even, and 1 (true) if the number is odd. A better name for the function would be isOdd(), but since the quiz asks for a function by the name isEven(), my solution would be as follows:

This code does what the name suggests, i.e. to evaluate whether or not the entered number is even (true/false), by using the ! (logical not) operator. It can still be a bit of a hassle to understand intuitively from an outsider's perspective by just looking at the code, which is (I assume) why Alex and Nascardriver chose their solution instead:

• Amir

you right :)  it makes sense . I wasn't caring that much about how to make code readable and easy to understand. Now after learning more I really see how its  important to make each statement clear . thank you :)