Skip to content

Commit e85127e

Browse files
Add generic root of a number [Hacktoberfest] TheAlgorithms#2533 (TheAlgorithms#2534)
1 parent d93492b commit e85127e

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Maths/GenericRoot.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/*
2+
* Algorithm explanation: https://technotip.com/6774/c-program-to-find-generic-root-of-a-number/#:~:text=Generic%20Root%3A%20of%20a%20number,get%20a%20single%2Ddigit%20output.&text=For%20Example%3A%20If%20user%20input,%2B%204%20%2B%205%20%3D%2015.
3+
*/
4+
public class GenericRoot {
5+
public static void main(String[] args) {
6+
int number1 = 1234;
7+
int number2 = 12345;
8+
int result1 = genericRoot(number1);
9+
int result2 = genericRoot(number2);
10+
System.out.println("Generic root of " + number1 + " is: " + result1);
11+
System.out.println("Generic root of " + number2 + " is: " + result2);
12+
}
13+
14+
private static int genericRoot(int n) {
15+
int root = 0;
16+
while (n > 0 || root > 9) {
17+
if (n == 0) {
18+
n = root;
19+
root = 0;
20+
}
21+
root += n % 10;
22+
n /= 10;
23+
}
24+
return root;
25+
}
26+
}

0 commit comments

Comments
 (0)