how can I add each digit in that number and check if that sum is divisible by 7

1) I want to find all the numbers below 1000 which are divisible by 3.

2) I successfully found all those numbers.

3) Now how can I add each digit in that number and check if that sum is divisible by 7?

Can anyone explain how to do this.

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

//This is a code that prints all the numbers below 1000 that are divisible by 3.
 #include <iostream>
using namespace std;

void divide()
{
	for (int i = 0; i <= 1000; i++)
	{
		if (i % 3 == 0)
		{
			cout << i << endl;
		}
	}
}

int main()
{
	int num;

	divide();

	system("pause");
	return 0;
}
Last edited on
http://www.cplusplus.com/forum/beginner/241311/

No, that's yours isn't it?


You can simply count up from 3 in 3's to ensure your number is divisible by 3.


There are many different ways to sum digits:-
- pick the digits off one by one with %10 (modulo operation) followed by integer-dividing the number by 10 to move to the next;
or ...
- take a string representation and add up the integer equivalents of the individual characters;
or ...
etc.


Or you can avoid summing digits altogether ...
Last edited on
Here's a few ways to sum digits. Feel free to add some more.

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
64
#include <iostream>
#include <numeric>
#include <string>
using namespace std;



int sumDigits1( unsigned long long n )                     // Recursive version using modulus and division (my preference)
{
   return n ? sumDigits1( n / 10 ) + n % 10 : 0;
}



int sumDigits2( unsigned long long n )                     // Non-recursive version using modulus and division (while loop)
{
   int sum = 0;
   while ( n )
   {
      sum += n % 10;
      n /= 10;
   }
   return sum;
}



int sumDigits3( unsigned long long n )                     // Non-recursive version using modulus and division (for loop)
{
   int sum = 0;
   for ( ; n; n /= 10 ) sum += n % 10;
   return sum;
}



int sumDigits4( unsigned long long n )                     // Via string characters
{
   int sum = 0;
   for ( char c : to_string( n ) ) sum += c - '0';
   return sum;
}



int sumDigits5( unsigned long long n )                     // Using std::accumulate()
{
   string str = to_string( n );
   return accumulate( str.begin(), str.end(), 0, []( int sum, char c ){ return sum + ( c - '0' ); } );
}



int main()
{
   int n = 1234321;
   cout << "Input n: ";   cin >> n;

   cout << sumDigits1( n ) << '\n';
   cout << sumDigits2( n ) << '\n';
   cout << sumDigits3( n ) << '\n';
   cout << sumDigits4( n ) << '\n';
   cout << sumDigits5( n ) << '\n';
}
Topic archived. No new replies allowed.