Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to calculate the greatest common divisor (GCD) of two numbers using Euclid's algorithm.
DSA Java
public static int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % [1];
a = temp;
}
return a;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using b % a instead of a % b
Using temp instead of a or b in modulo
Replacing b with 0 prematurely
✗ Incorrect
In Euclid's algorithm, we replace b with a % b. So the blank should be 'b' to compute a % b.
2fill in blank
mediumComplete the code to check if a number n is prime by testing divisibility up to its square root.
DSA Java
public static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= [1]; i++) {
if (n % i == 0) return false;
}
return true;
}Attempts:
3 left
💡 Hint
Common Mistakes
Checking divisibility up to n-1 which is inefficient
Using n/2 which is more than needed
Not casting Math.sqrt(n) to int
✗ Incorrect
To check primality efficiently, we test divisibility up to the square root of n.
3fill in blank
hardFix the error in the code to compute the modular exponentiation (a^b mod m) efficiently.
DSA Java
public static long modExp(long a, long b, long m) {
long result = 1;
a = a % m;
while (b > 0) {
if ((b & [1]) == 1) {
result = (result * a) % m;
}
a = (a * a) % m;
b >>= 1;
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using (b & 0) which is always 0
Using (b & 2) which checks the second bit
Using (b & b) which is always b
✗ Incorrect
To check if the least significant bit of b is set, we use (b & 1) == 1.
4fill in blank
hardFill both blanks to create a map of numbers to their squares for numbers greater than 3.
DSA Java
Map<Integer, Integer> squares = new HashMap<>(); for (int num = 1; num <= 5; num++) { if (num [1] 3) { squares.put(num, num [2] num); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' in the condition
Using '**' which is not valid in Java
Using '+' instead of '*' for squaring
✗ Incorrect
We want numbers greater than 3, so use '>'. To square, use multiplication '*'.
5fill in blank
hardFill all three blanks to create a filtered map of uppercase keys to values greater than 10.
DSA Java
Map<String, Integer> filtered = new HashMap<>(); for (Map.Entry<String, Integer> entry : data.entrySet()) { if (entry.getValue() [1] 10) { filtered.put(entry.getKey().[2](), entry.getValue()); } } int size = filtered.[3]();
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' in the condition
Using toLowerCase() instead of toUpperCase()
Using containsKey() instead of size() to get map size
✗ Incorrect
We check if value > 10, convert key to uppercase with toUpperCase(), and get map size with size().
