Write Code vs. Write Poetry: ThreeAndFive (Math)
Question: write an algorithm to find sum of numbers which are smaller than N and divisible by 3 or 5Example:
N = 9 => 3 + 5 + 6 = 14
N = 10 => 3 + 5 + 6 + 9 = 23
Idea: Arithmetic progression and inclusion-exclusion principle.
The sum of 3's and 5's = The sum of 3's+ The sum of 5's - The sum of 15's. Take care the question asks for smaller than, so 9 does not count if the input is 9.
Time: O(1) Space: O(1)
Read full article from Write Code vs. Write Poetry: ThreeAndFive (Math)
No comments:
Post a Comment