Search code examples
csumdigits

Output a number with specified length and sum


I have to make a program in C, which accepts to integers, sumOfDig and lengthOfNum. sumOfDig equals the sum of the digits and lengthOfNum equals the length of the number. I am not allowed to use arrays or the math.lib

1 ≤ sumOfDig ≤ 81 and 1 ≤ lengthOfNum ≤ 9

I tried to write a while loop, but I can't think of a way that can build a number and subtract the last added number from the sum of the numbers.

#include <stdio.h>
#include <stdlib.h>

int main() {
    int lengthOfNum;     /* stores the length of the number       */
    int sumOfDig;        /* stores the sum of the digits          */
    int ans;             /* stores the answer                     */

    scanf("%d", &sumOfDig);     /* scans the sum of the digits    */
    scanf("%d", &lengthOfNum);  /* scans the length of the number */

    ans=0;     /* initializes ans */

    /* adds a number to ans, and removes it from sumOfDig */
    while(sumOfDig!=0 && lengthOfNum!=0) {
        /*???*/

        lengthOfNum--;
    };

    printf("%d\n", ans);     /* prints the outcome */

    return 0;
}

The following should be the input and outcome:

In: 20 2 Out: Not possible

In: 20 3 Out: 992 (since the length is 3 and 9+9+2=20)

In: 50 8 Out: 99999500 (since the length is 8 and 9+9+9+9+9+5+0+0=50)


Solution

  • Let's call the sum of digits S and the specified length L.

    First, we need to check if there's a solution. The minimum number of digits we need will depend on how many times 9 divides into S.

    1. Find how times 9 divides into S. Let's call this Q.
    2. Find the remainder of the aforementioned division. Let's call this R.
    3. If R is 0,
      1. If the L is less than Q,
        1. No solution.
    4. Else,
      1. If the L is less than Q+1,
        1. No solution.

    Now, we can produce the output.

    1. Output Q 9s.
    2. If R isn't 0,
      1. Output R.
      2. Output L-Q-1 0.
    3. Else
      1. Output L-Q 0.

    or

    1. Output Q 9s.
    2. Set Z to L-Q.
    3. If R isn't 0,
      1. Output R.
      2. Decrement Z.
    4. Output Z 0.

    There are other approaches. You could avoid checking the inputs first by building the output in a buffer —or even in an int— but I used one that's easy to visualize and follows the often-required convention of validating before calculating.

    Division can be done as a loop, and this gives you the basis for the alternate approaches I mentioned.

    unsigned R = S;
    unsigned Q = 0;
    while (R > 9) {
       R -= 9;
       ++Q;
    }