Modular arithmetic keeps numbers within a fixed range, preventing overflow and making calculations efficient. This is crucial in algorithms involving large numbers.
int gcd(int a, int b) { while (b != 0) { int temp = b; b = a % b; a = temp; } return a; } int main() { int result = gcd(48, 18); std::cout << result << std::endl; return 0; }
The greatest common divisor (GCD) of 48 and 18 is 6. The Euclid's algorithm iteratively computes this by replacing the pair with (b, a % b) until b is zero.
bool isPrime(int n) { if (n <= 1) return false; for (int i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true; } int main() { std::cout << isPrime(29) << std::endl; std::cout << isPrime(30) << std::endl; return 0; }
The function returns true (1) for 29 because it is prime, and false (0) for 30 because it is not prime.
int modExp(int base, int exp, int mod) { int result = 1; for (int i = 0; i < exp; i++) { result = (result * base) % mod; } return result; } int main() { std::cout << modExp(2, 10, 1000) << std::endl; return 0; }
The code correctly computes modular exponentiation by applying modulo at each multiplication step. The output is (2^10) % 1000 = 1024 % 1000 = 24.
The total number of divisors is the product of (exponent + 1) for each prime factor.
