program to count how many numbers between 1 and 10000 are divisible by 3

Jun 1, 2016 at 8:18pm
Write a program to count how many numbers between 1 and 10000 are divisible by 3 with no remainder. (You must use a for loop in your code).
Jun 1, 2016 at 8:22pm
With a for-loop you cycle through all the numbers from 1 to 10000. With a variable you count how many of them are divisible by 3.

1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{
    int counter = 0;

   for(int i = 1; i<=10000; i++)
   {
       if(i % 3 == 0)
         counter++;
   }

    cout << counter;
}
Last edited on Jun 1, 2016 at 8:23pm
Jun 1, 2016 at 8:25pm
thank you for the help
Jun 2, 2016 at 3:08am
You could just calculate the number directly with a little algebra...
Jun 2, 2016 at 4:26pm
Pretty much what Duoas said...

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 <iostream>
#include <cmath>
using namespace std;
int main() {
	double input, divisor;
	while (true) {
		cout << "Enter in a number: ";
		cin >> input;
		cout << "What divisor specific nums would you like to calculate: ";
		cin >> divisor;

		int calculate = floor(input / divisor);
		int forCount = 0;
		for (int i = divisor; i <= input; i++) {
			if (i % static_cast<int>(divisor) == 0) {
				forCount++;
			}
		}
		cout << "\nFor loop calculated: " << forCount
			<< " the math calculation was: " << calculate;
		cout << '\n';
	}
	cin.ignore();
	cin.get();
	return 0;
}
Last edited on Jun 2, 2016 at 4:26pm
Jun 2, 2016 at 4:54pm
A little algebra, I guess what Duoas was thinking:

int count = 10000/3;


Last edited on Jun 2, 2016 at 4:55pm
Topic archived. No new replies allowed.