Sum of Multiples
Given an array of integers and a specific target number, write a function that returns the sum of all elements in the array that are multiples of the target number.
[ 10, 3, 5, 18, 20, 21 ]
Explanation. Multiples of 3 in the array are [3, 18, 21]. The sum of these multiples is 3 + 18 + 21 = 42. Similarly, Multiples of 5 are [5, 20]. The sum of these multiples is 5 + 20 = 25. Hence total sum is 42 + 25 = 63.
[ 7, 22, 5, 13, 10 ]
Explanation. Multiples of 5 in the array are [5, 10]. The sum of these multiples is 5 + 10 = 15.
[ 8, 16, 32 ]
Explanation. Multiples of 8 in the array are [8, 16, 32]. The sum of these multiples is 8 + 16 + 32 = 56.
Follow-up: Can you optimize your solution to run in O(n) time complexity?
The input array should have at least one integer and the target number will always be a positive integer greater than zero.
- Views
- 2