Skip to content

Sum Of Multiples

Intro

If we list all the natural numbers below 20 that are multiples of 3 or 5,

we get 3, 5, 6, 9, 10, 12, 15, and 18.

The sum of these multiples is 78.

Task

Given a number, find the sum of all the unique multiples of particular numbers up to but not including that number.

The Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include "sum_of_multiples.h"
#include <cstdint>
#include <vector>
#include "list"

namespace sum_of_multiples {
int to(std::vector<int> test, int test2)
{
    std::list<int> tmp{};
    std::uint32_t result{};
    for(auto a:test) {
        for(int i=a; i<test2; i+=a)
        {
            tmp.push_back(i);
        }
    }
    tmp.sort();
    tmp.unique();
    for(auto a:tmp)
    {
        result+=a;
    }

    return result;
}
}  // namespace sum_of_multiples
1
2
3
4
5
6
7
8
9
#include <vector>
#if !defined(SUM_OF_MULTIPLES_H)
#define SUM_OF_MULTIPLES_H

namespace sum_of_multiples {
int to(std::vector<int>,int);
}  // namespace sum_of_multiples

#endif // SUM_OF_MULTIPLES_H

Last update: February 10, 2021

Comments