프로그래밍/C, C++
The C++ Modulus Operator
잡초사랑
2011. 6. 7. 14:15
The C++ Modulus Operator
Take a simple arithmetic problem: what's left over when you divide 11 by 3? The answer is easy to compute: divide 11 by 3 and take the remainder: 2. But how would you compute this in a programming language like C or C++? It's not hard to come up with a formula, but the language provides a built-in mechanism, the modulus operator ('%'), that computes the remainder that results from performing integer division.If you wanted to know if a number was odd or even, you could use modulus to quickly tell you by asking for the remainder of the number when divided by 2.
#include <iostream> using namespace std; int main() { int num; cin >> num; // num % 2 computes the remainder when num is divided by 2 if ( num % 2 == 0 ) { cout << num << " is even "; } return 0; }The key line is the one that performs the modulus operation: "num % 2 == 0". A number is even if and only if it is divisible by two, and a number is divisible by another only if there is no remainder.
How could you use modulus to write a program that checks if a number is prime?