Title: Given a number n, the number of all the numbers that can be divisible by 3 or 5 is not more than N. For example: n = 9, answer 3 + 6 + 5 + 9 = 23. Ideas:
What are the numbers that can be divisible by 3 or 5?
Number divisible by 3:3,6,9 .... [N/3]*3
Number divisible by 5:5,10,15 ... [N/5]*5
Number of repetitions (the number divisible by 3 and 5, which is divisible by 15): 15,30 ... [n/15]*15
So the answer to the question is obvious:
Sum of the sum of the numbers divisible by 3 or 5 and = the sum of the numbers divisible by 5 and the number of the numbers divided by 15-the sum of the numbers divisible by the sum
Because the sum of the sequence is arithmetic progression, the use of arithmetic progression summation formula can be easily solved.
- X is the first item, Y is the number of items, and D is the tolerance
- (x + x + d * (y–1)) * Y/2, note y = 0 also applicable
Code:
#include <iostream>using namespace Std;int sumofarithmeticseries (int x,int c,int d) { return (x+x+ (c-1) *d) *c/ 2;} int main () { int sum_3=0,sum_5=0,sum_15=0; int n=9; int sum=0; Sum_3=sumofarithmeticseries (3,n/3,3); Sum_5=sumofarithmeticseries (5,n/5,5); Sum_15=sumofarithmeticseries (15,n/15,15); sum=sum_3+sum_5-sum_15; cout<<sum<<endl; return 0;}
(written question) The sums of the numbers divisible by 3 and 5