Skip to content

Commit b9efcbb

Browse files
Merge pull request #653 from G7-TheKing/master
Added Java implementations of Euler's Totient Function and Tower of Hanoi
2 parents 9a81eb0 + 2a20ec0 commit b9efcbb

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

Math/TowerofHanoi/toh.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Java recursive program to solve tower of hanoi puzzle
2+
3+
class GFG
4+
{
5+
// Java recursive function to solve tower of hanoi puzzle
6+
static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
7+
{
8+
if (n == 1)
9+
{
10+
System.out.println("Move disk 1 from rod " + from_rod + " to rod " + to_rod);
11+
return;
12+
}
13+
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
14+
System.out.println("Move disk " + n + " from rod " + from_rod + " to rod " + to_rod);
15+
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
16+
}
17+
18+
// Driver method
19+
public static void main(String args[])
20+
{
21+
int n = 4; // Number of disks
22+
towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods
23+
}
24+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// A simple java program to calculate
2+
// Euler's Totient Function
3+
import java.io.*;
4+
5+
class GFG {
6+
7+
// Function to return GCD of a and b
8+
static int gcd(int a, int b)
9+
{
10+
if (a == 0)
11+
return b;
12+
return gcd(b % a, a);
13+
}
14+
15+
// A simple method to evaluate
16+
// Euler Totient Function
17+
static int phi(int n)
18+
{
19+
int result = 1;
20+
for (int i = 2; i < n; i++)
21+
if (gcd(i, n) == 1)
22+
result++;
23+
return result;
24+
}
25+
26+
// Driver code
27+
public static void main(String[] args)
28+
{
29+
int n;
30+
31+
for (n = 1; n <= 10; n++)
32+
System.out.println("phi(" + n + ") = " + phi(n));
33+
}
34+
}

0 commit comments

Comments
 (0)