Hey, need some help with exercise I was given at school.
Need to write and algorithm to find the smallest natural number if I have only its digits sum and product.
For example if I get 3 2 the smallest number will be 12 as 1 + 2 = 3 and 1 * 2 = 2.
And if I got for example 3 4 the number doesn't exist.
constchar d[] = "Data.txt";
void reading (int & x, int & y);
vector<int> division (int i);
int sum (vector <int> a);
int product (vector <int> a);
void checking (int x, int y);
int main()
{
int x, y;
reading (x, y);
checking (x, y);
return 0;
}
void reading (int & x, int & y) // Reads sum and product from file
{
ifstream in (d);
in >> x >> y;
in.close ();
}
void checking (int x, int y) // Checks if numbers digits match the needed sum and project
{
int i = 0;
vector<int> a;
do
{
i++;
a = division (i);
}
while (x != sum(a) || y!= product (a));
cout << i;
}
vector<int> division (int i) // Divides number in to its digits
{
vector<int> a;
while (i > 0)
{
a.push_back(i % 10);
i /= 10;
}
return a;
}
int sum (vector <int> a) // Counts sum
{
int s = 0;
for (int i = 0 ; i < a.size () ; i++)
{
s += a[i];
}
return s;
}
int product (vector <int> a) // Counts product
{
int s = 1;
for (int i = 0 ; i < a.size () ; i++)
{
s *= a[i];
}
return s;
}
It works just fine if sum and product given are correct, but if the number doesn't exist the program crashes
First, not sure your input file is.
Second, there is a logic error in the division function. You should use do-while loop.
Third, you haven't set up a terminating condition for a number of cases in which the smallest natural number can never be calculated. Your program just simply runs out of memory if you let it run for forever.
Fourth, your program seems short but hard to read. Your program output is not that rich and informative, so it is hard to debug. In some cases, using functions for every little thing is not a very good idea. You can just write everything in the main() function instead.