Data Structures & AlgorithmsModerateTCS NQT · number theory
Problem: How many pairs (i < j) of [2, 3, 4, 5, 6] have gcd(a[i], a[j]) = 1? Run the code.
Problem: How many pairs (i < j) of [2, 3, 4, 5, 6] have gcd(a[i], a[j]) = 1? Run the code.
from math import gcd a = [2, 3, 4, 5, 6] print(sum(1 for i in range(len(a)) for j in range(i + 1, len(a)) if gcd(a[i], a[j]) == 1))What is printed?
- A. 4
- B. 12
- C. 7
- D. 6
Correct answer: D. 6
The coprime pairs are (2,3), (2,5), (3,4), (3,5), (4,5) and (5,6), giving 6 of the 10 pairs. Counting the pairs that share a factor gives 4, counting ordered pairs doubles it to 12, and testing 'neither divides the other' instead of gcd = 1 gives 7 because it wrongly admits (4,6).
More Coding Interview Problems questions
- What does this Python program print? python a = [2, -2, 3, -3, 1, 1] p = {0: 1}; s = 0; ans = 0 for x in a: s += x ans += p.get(s, 0) p[s]…
- What does this program print? python from collections import Counter a = [3, 1, 2, 3, 1, 2, 3] c = Counter(a) pairs = sum(v (v - 1) // 2…
- What does this program print? python a = [6, 3, 8, 1] mx = [0] len(a) mx[-1] = a[-1] for i in range(len(a) - 2, -1, -1): mx[i] = max(a[i]…
- Array a = [7, -3, 2, 5, -8, 4, 1, -1]. How many contiguous subarrays have a sum divisible by 3? (Zero is divisible by 3.)
- Sorted list [3, 6, 9, 12, 15, 18, 21]. How many index triples i < j < k satisfy vals[i] + vals[j] = vals[k]?
- How many contiguous subarrays of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] sum to exactly 15?