Write the program that will compute for and display the sum of all numbers divisible by 3 from 1 to 1000.
#include <iostream>
using namespace std;
int main()
{
int sum = 0;
// simple approach: traverse all numbers from 1 to 1000
// and check if current number is divisible by 3
for (int i = 1; i <= 1000; i++) {
if (i % 3 == 0) {
sum += i;
}
}
cout << sum << endl;
// another approach: we know that having a
// number divisible by 3, we can find the next
// number by adding 3 to the current.
// The first divisible number is 3
sum = 0;
for (int i = 3; i <= 1000; i += 3) {
// no need to check, we only jump on divisible numbers
sum += i;
}
cout << sum << endl;
}
Comments
Leave a comment