Data Structures & AlgorithmsModerateTCS NQT · number theory
Problem: What is the sum of gcd(i, j) over all pairs 1 <= i < j <= 4? Run the code.
Problem: What is the sum of gcd(i, j) over all pairs 1 <= i < j <= 4? Run the code.
from math import gcd print(sum(gcd(i, j) for i in range(1, 5) for j in range(i + 1, 5)))What is printed?
- A. 7
- B. 17
- C. 14
- D. 5
Correct answer: A. 7
The six pairs have gcds 1, 1, 1, 1, 2, 1 (only (2, 4) shares a factor), totalling 7. Starting j at i adds gcd(i, i) = 1 + 2 + 3 + 4 and gives 17, summing over ordered pairs doubles it to 14, and counting the coprime pairs instead of summing gcds gives 5.
More Coding Interview Problems questions
- Problem: What is the digit sum of 2^100? Run the code. python print(sum(int(c) for c in str(2 100))) What is printed?
- Problem: How many triples (a, b, c) with 1 <= a <= b <= c <= 10 have a + b + c = 12? Run the code. python print(sum(1 for a in range(1…
- Problem: What is the largest prime factor of 600851475143? Run the trial-division code. python n = 600851475143 f = 2 last = 1 while f f…
- Problem: How many integers in [1, 999] are divisible by 7 but not by 14? Run the code. python print(sum(1 for x in range(1, 1000) if x % 7…
- Problem: How many ordered pairs (i < j) of [1, 2, 3, 4, 6] have a[j] divisible by a[i]? Run the code. python a = [1, 2, 3, 4, 6]…
- Problem: What is the minimum number of operations to go from 1 to 10 when each operation is +1 or 2? Run the BFS. python from collections…