Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic root of a number in c

Tags:

c

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

like image 377
poorvank Avatar asked May 27 '13 09:05

poorvank


People also ask

What is 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.

What is generic root of a number in Python?

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.


1 Answers

A number n modulus 9 returns either its root or 0, in which case the root is 9.

  1. Calculate n % 9 to get the root
  2. If the result is 0, then 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.

like image 103
John Willemse Avatar answered Oct 06 '22 01:10

John Willemse