(written question) The sums of the numbers divisible by 3 and 5

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.