Problem 1

Add all the natural numbers below one thousand that are multiples of 3 or 5.

This is a simple enough problem. First thing to note is that the “or” in this problem is not an exclusive or, that is, multiples of 3 and 5 (i.e. 15) are counted. This is an example of a FizzBuzz problem.

In Python:

print sum([x for x in range(1000) if (x%3==0 or x%5==0)])

In C++:

#include <iostream>

using namespace std;

int main()
{

    int total=0;
    for(int i=1; i<1000; ++i)
    {
        if (i%3==0 || i%5==0) total+=i;
    }

    cout << total << endl;

    return 0;

}

The answer is 233168.

Advertisements
This entry was posted in Problems. Bookmark the permalink.

Leave a Reply

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s