Question

This is not a school work or my assignment. In fact, I came out with this question. I have been researching and testing the possibilities of using ONLY a single while loop with basic operators like +-*/% and basic variables like int value to perform tasks. I want to find out how much it can achieve without using any other control structures.

This is my programing question:

Use a single while loop to sum up all digits of a positive number until it becomes a single digit. For example:

778899 becomes 7+7+8+8+9+9=48. 
48 becomes 4+8=12. 
12 becomes 1+2=3. 
Final number is 3.

This question is extremely easy if we are allowed to use conditional statements. But, can we still solve it if we cannot use:

-any conditional statements (if/switch case)
-any ternary operators
-any function calls
-any recursive calls
-any other data structures like arrays/lists/vectors/pointers..
-any bit shift operators

Note: I am not discussing whether or not it can be solved. I know it can be done.

Was it helpful?

Solution

It's very simple, actually:

int singleDigitSum(int n) {
  int sum = n % 9;
  while (sum == 0) {
    sum += 9;
  }
  return sum;
}

Explanation: for a given number N, this single digit sum is actually either the remainder of N divided by 9, or, if that remainder is 0, 9 itself. So loop here is used only to 'fast-forward' the result to 9 in that last case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top