Generic root of a number is defined as the sum of digits of a number until we get a single digit. For example:
Generic root of 456: 4 + 5 + 6 = 15 since 15 is two digit numbers so 1 + 5 = 6
So, generic root of 456 = 6
I solved this problem by recursively adding the digits of the number until a single digit number is obtained and the program worked fine. I searched the web and found a very small solution for it which i was unable to understand:
#include<stdio.h>
int main()
{ int n,x;
printf("Enter no");
scanf("%d",&n);
printf("Generic root: %d",(x=n%9)?x:9);
return 0;
}
I am not able to understand how the ternary operator is working here!? How is it calculating the Generic root of a number
Generic root of a number is the sum of all the digits of a given number until we get a single digit output. For example, if a number is 428, then it's generic root will be 4 + 2 + 8 = 14, then 1 + 4 = 5.
The generic root of a number is the sum of all digits until the sum is less than 10. For instance, generic root of 98 = 9 + 8 = 17 => 1 + 7 = 8. To achieve this, we used nested for loop (for sum = 0; genNumber > 0; genNumber = genNumber / 10) to find the sum of digits.
A number n modulus 9 returns either its root or 0, in which case the root is 9.
So (x=n%9)?x:9
means that if n mod 9 is zero, assign 9.
You can also achieve this without the ternary operator:
x = 1+((n-1)%9)
The modulus 9 trick is called the congruence formula.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With