- #1
tawi
- 33
- 0
Homework Statement
Make an "absolute sum of digits" of a number in a particular numerical system. You are given two numbers (numerical system and your number N). You take the number N, add up its digits, if the result has more than one digit you add them up again and so on. You end up with one-digit result.
Example:
1) You are given numbers 10, 555. 10 is your numerical system so we are in decimal and you are adding up the digits of 555. So 5 + 5 + 5 = 15 but because it has more than two digits you add them up again and your result is 1 + 5 = 6.
2) 2, 255. We are in binary and 255 in binary equals to 11111111. We add those ones up and get 8. 8 in binary is 1000, we add that up and 1 will be our output.
Homework Equations
I´ve made a program that does all this but there is a loophole where, for certain numbers, it won´t work.
The problem is that, if you look at the code below, there is the second while cycle for sum>0... Take the number 5996 in decimal for instance and go through the first cycle that determines its "first" sum of digits in that particular system... We get a correct result 29. Now go through the second cycle that should continue adding up its digits until sum<=0.
But if you take 29 through that cycle on the first pass you get: y=9, sum=2, result=9.
Second pass: y=2, sum=0, result = 11. Our sum is 0 and thus the cycle stops but our result still has two digits and we still need to add those ones up. Obviously there needs to be some different or extended condition for the second while cycle but I don´t know how to achieve what I want.
Of course I could just put a condition at the end and ad those two digits up separately but what if the same happens and the number has three digits?
I can´t do (while result > 9) instead of (while sum > 0) because the result starts at zero and goes up so it makes no sense.
The Attempt at a Solution
Code:
program abcd;
var system, N, x, y, sum, result : integer;
begin
readln(system);
readln(N);
while N > 0 do
begin
x := (N mod system);
N := (N div system);
sum := (sum + x);
end;
while sum > 0 do
begin
y := (sum mod system);
sum := (sum div system);
result := (result + y);
end;
writeln(result);
end.
EDIT: hmm, after some thinkink I figured I can just put another while cycle (similar to the first one) at the end that would again simply made a sum of the digits of the result of the second while cycle (result). It doesn´t seem that sophisticated but I guess it should work for most numbers. Exception being some huge number that even after the second cycle and the third cycle still consists of more than one digit. No idea how to go around that.
Last edited: