In Java Language 1. Write a recursive method expFive(n) to compute y=5^n. For in
ID: 3733661 • Letter: I
Question
In Java Language 1. Write a recursive method expFive(n) to compute y=5^n. For instance, if nis 0, y is 1. If n is 3, then y is 125. If n is 4, then y is 625. The recursive method cannot have loops. Then write a testing program to call the recursive method. 2. For two integers m and n, their GCD(Greatest Common Divisor) can be computed by a recursive function. Write a recursive method gcd(m,n) to find their Greatest Common Divisor. Once m is 0, the function returns n. Once n is 0, the function returns m. If neither is 0, the function can recursively calculate the Greatest Common Divisor with two smaller parameters: One is n, the second one is m mod n. Although there are other approaches to calculate Greatest Common Divisor, your program should follow the instructions of this question, otherwise you will not get the credit. Then write a testing program to call the recursive method.
Explanation / Answer
import java.util.*;
import java.lang.*;
import java.io.*;
// this calss is for implementing expFive & GCD menthods recursively
class recursion
{
// This method caluclate the exponentFive of given n by using recursion. i.e 5^n
public int expFive(int n){
if(n==0) return 1;
else return (5*expFive(n-1)); // recursive calling
}//expFive method ends.
// this method caluclate the gcd of given two numbers by recursion
public int GCD(int m , int n){
if(m==0) return n;
else if(n==0) return m;
else if(m<n) return GCD(m,n%m);
else return GCD(m%n,n);
}//GCD method ends
}//class recursion ends
// this testing class for calling the recursive methods in recursion class
class testing
{
public static void main (String[] args) throws java.lang.Exception{
int m,n,p,gcd;
long y;
System.out.println("enter the value to which five exponent have to find i.e 5^n");
Scanner s= new Scanner(System.in);
n=s.nextInt();
recursion rs= new recursion(); //object creataion for recurion class.
y=rs.expFive(n); // expFive method calling
System.out.println("exponentFive of"+" "+ n+ " is:"+" "+y);
System.out.println("enter the values m & n to find GCD");
m=s.nextInt();
n=s.nextInt();
gcd=rs.GCD(m,n);
System.out.println("Gcd of given two numbers is:"+" "+gcd);
} // main method ends
} //class testing ends
input:
10 // for finding exponent FIve i.e 5^n
48 18 // two numbers for finding GCD
output:
enter the value to which five exponent have to find i.e 5^n
exponentFive of 10 is: 9765625
enter the values m & n to find GCD
Gcd of given two numbers is: 6
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.