Complete the code to calculate the greatest common divisor (GCD) of two numbers using Euclid's algorithm.
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % [1];
a = temp;
}
return a;
}The Euclid's algorithm uses the remainder of a divided by b, so the blank should be 'b' to compute 'a % b'.
Complete the code to check if a number 'n' is prime by testing divisibility up to its square root.
#include <math.h> int is_prime(int n) { if (n <= 1) return 0; for (int i = 2; i <= [1]; i++) { if (n % i == 0) return 0; } return 1; }
To check primality efficiently, we only need to test divisors up to the square root of 'n'.
Fix the error in the code to compute the modular exponentiation (a^b mod m) efficiently.
int mod_exp(int a, int b, int m) {
int result = 1;
a = a % m;
while (b > 0) {
if (b [1] 1) {
result = (result * a) % m;
}
a = (a * a) % m;
b = b / 2;
}
return result;
}To check if the least significant bit of 'b' is set (odd number), use bitwise AND '&' with 1.
Fill both blanks to create a function that returns the least common multiple (LCM) of two numbers using their GCD.
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % temp;
a = temp;
}
return a;
}
int lcm(int a, int b) {
return (a [1] b) / [2](a, b);
}The LCM of two numbers is their product divided by their GCD.
Fill all three blanks to create a function that counts how many numbers in an array are divisible by a given divisor.
int count_divisible(int arr[], int size, int divisor) {
int count = 0;
for (int i = 0; i < size; i++) {
if (arr[i] [1] divisor == [2]) {
count [3];
}
}
return count;
}To check divisibility, use modulo operator '%' and compare to 0. Increment count with '++'.
