-
Notifications
You must be signed in to change notification settings - Fork 0
/
1.txt
23 lines (18 loc) · 1.11 KB
/
1.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Given a number N calculate the sum of 3 and 5 multiples. This is a simple progression, series question. The idea is to provide a constant time and space solution that is O(1).
Calculate number of 3 multiples from by (n-1)/3. Dividing n-1 by 3 because the multiples must be strictly less than n. Similarly calculate number of 5 and 15 multiples. Later calculate sum of 3 multiples, 5 multiples and 15 multiples using the standard summation formula,
S = (n(a+l))/2
a - first number of the series
l - last number of the series
n - number of terms in the series
Add sum of three multiples(i.e, sum3) with sum of 5 multiples and substract sum of 15 multiples, we substract 15 multiples because they occur both in 3 and 5 multiples. Hence the final result will be,
sum3 + sum5 - sum15
Code:
ll n;
cin >> n;
ll k = (n - 1) / 3; // number of 3 multiples below n.
ll l = (n - 1) / 5; // number of 5 multiples below n.
ll m = (n - 1) / 15; // number of 15 multiples below n.
ll sum3 = (k * (3 + (k * 3))) / 2;
ll sum5 = (l * (5 + (l * 5))) / 2;
ll sum15 = (m * (15 + (m * 15))) / 2;
cout << (sum3 + sum5 - sum15);