Coding Challenge #1 – Sum of multiples

Here is a little coding challenge to try.

The objective is to find the sum of multiples within a given range.

For example assume that given multiples are 4, 5 and 7. The upper limit is 20 (excluding). Multiples of 4 within 20 are 4, 8, 12 and 16. Then multiples of 5 within 20 are 5, 10 and 15. The multiples of 7 within 20 are 7 and 14. The objective is to find the sum of all those numbers.

The upper limit and the number of multiples can be vary from problem to problem.

Solution in Cpp

#include <iostream>

using namespace std;

int isMult(int mult[], int n, int length);

int main () {
    int no_of_mult = 2;
    int multiSet[no_of_mult] = {3, 5};
    int upper_limit = 10;
    
    int sum = 0;
    for (int i=0; i &lt; upper_limit; i++){
        sum = sum + isMult(multiSet, i, no_of_mult);
    }
    cout &lt;&lt; "Sum = " &lt;&lt; sum;
}

int isMult(int mult[], int n, int length){
    for(int i =0; i &lt; length; i++){
        int r = n % mult[i];
        if(r == 0){
            return n;
        }
    }
    return 0;
}

Try it online http://tpcg.io/ujmQDD

Advertisements

Please add your valuable idea below, will make a discussion, thanks !

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s