Digits sum and product

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.
.
Last edited on
can you show us the code you have done so far?
This is what I've got

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const char 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
Last edited on
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.
Last edited on
Topic archived. No new replies allowed.