I enjoy finding problems to solve with code. I found a page on the internet this afternoon that asked for the sum of all integers between 1 and 1,000 that are divisible by either 3 or 5. I immediately thought of the FizzBuzz program I wrote a while back, and realized the algorithm is actually quite similar. It’s just what you do with those threes and fives that’s different in this case. Either way, it was a fun couple of minutes putting to code what I’d been mulling over.
~Jonathan
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | // ================================================== // Programmer: Jonathan Landrum // Date: 31 January 2012 // ================================================== // Program: threeOrFive.cpp // Purpose: Adds the integers between 1 and 1,000 // that are divisible by either 3 or 5. // Assumptions: None. // ================================================== #include <iostream> #include <string> using namespace std; // -------------------------------------------------- // main(): // Does ALL the things! // -------------------------------------------------- int main () { // ---------------------------------------------- // Declare variables, not war // ---------------------------------------------- int sum = 0; int c = 3; // ---------------------------------------------- // Introduce the program // ---------------------------------------------- cout << endl; cout << "----------------------------" << endl; cout << "- Sum of 3's and 5's -" << endl; cout << "----------------------------" << endl; cout << endl; cout << "This program adds together the" << endl; cout << "integers between 1 and 1,000" << endl; cout << "that are divisible by 3 or 5." << endl; cout << endl; // ---------------------------------------------- // Main processing loop // ---------------------------------------------- while (c < 1000) { if (c % 3 == 0 || c % 5 == 0) { sum += c; cout << c << endl; } else if (c % 3 == 0) { sum += c; cout << c << endl; } else if (c % 5 == 0) { sum += c; cout << c << endl; } // end if c++; } // end while // ---------------------------------------------- // Return the answer // ---------------------------------------------- cout << sum << endl; return (0); } // End main |

