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)
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.
Now, we can produce the output.
9
s.0
.0
.or
9
s.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;
}