It's supposed to find the numbers for which their digits' sum equals their digits' product. For example, taking the number 123: 1+2+3=6 and 1*2*3=6. So the program has to find and display the first 20 such numbers.
The code bellow runs perfectly except one thing. It displays ALL such numbers. I don't know how to make it stop after displaying the first 20.
I have tried including the main function's content in for and do/while loops but I've had no result so far.
Any ideas on how to make it stop after displaying the first 20 numbers in which the digit sum equals the product?
Much appreciated!
#include <iostream>
usingnamespace std;
int somme ( int n);
int produit( int n);
bool somme_produit_egaux( int n);
int main()
{
int n(11);
while ( n > 10)
{
if (somme_produit_egaux(n))
{
cout << n << ", ";
};
n++;
};
return 0;
}
int somme ( int n)
{
int r, answer(0);
while(n != 0)
{
r = n % 10;
n = n / 10;
answer = answer + r;
}
return answer;
}
int produit( int n)
{
int r, answer(1);
while( n != 0)
{
r = n % 10;
n = n / 10;
answer = answer * r;
}
return answer;
}
bool somme_produit_egaux( int n)
{
return somme(n) == produit(n);
}
#include <iostream>
#include <iomanip>usingnamespace std;
int somme ( int n);
int produit( int n);
bool somme_produit_egaux( int n);
int main()
{
int n(11);
int contor = 0;while ( n > 10)
{
if (somme_produit_egaux(n))
{
++contor;
cout << setw(4) << contor << setw(8) << n << '\n';
}
if(contor > 19)return 0;
n++;
}
return 0;
}
int somme ( int n)
{
int r, answer(0);
while(n != 0)
{
r = n % 10;
n = n / 10;
answer = answer + r;
}
return answer;
}
int produit( int n)
{
int r, answer(1);
while( n != 0)
{
r = n % 10;
n = n / 10;
answer = answer * r;
}
return answer;
}
bool somme_produit_egaux( int n)
{
return somme(n) == produit(n);
}
setw() is part of the C++ <iostream> library that allows you to format the output of cout. What it does is tell cout to print the output to take up a certain amount of space, regardless of how many digits/characters are actually output.