Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
Find if digital root of n is prime or not. DigitalRoot of a number is the repetitive sum of its digits until we get a single digit number.?
we get input as t(test cases) and for each test case, n(number), and output is 1 if digital root is prime, else 0.My code is not working for no.s such as 98.plz help.Code in link https://ide.geeksforgeeks.org/ntGwUdHSjk
C program to Find if digital root of n is prime or not. DigitalRoot of a number is the repetitive sum of its digits until we get a single digit number.?
1 Answer
- husoskiLv 73 years ago
The digital root of a positive number n is the almost the same as the remainder from division by 9. The only difference is that a positive multiple of 9 has a digital root of 9, but a remainder of 0.
Since neither 0 nor 9 are prime numbers, that doesn't make any difference for your final output. For all integers n>0, the digital root of n is prime if and only if (n%9) is prime.
But, if you want to display the correct value of the digital root, it does matter. An easy way to get the root without looping in C-like languages:
int root = (n + 8)%9 + 1;
If you've learned the switch statement, you can use that with cases 2, 3, 5, 7 coded to handle a prime digital root, and the other (default:) cases handling a non-prime root.
A faster method, with maybe even smaller code+data program size, is to use an array as a lookup table:
const char sieve[] = "nnPPnPnPnn";
...
bool is_prime = (n>0) && (sieve[n%9] == 'P');
Add <stdbool.h> to your includes at the top to get the standard bool type, plus the constants true and false, defined. (For old, pre-C99 compilers use int instead of bool.)


