Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

long factorial() returns the factorial x! ( x! = x(x-1)(x-2)(x-3)..(2)(1) ) int

ID: 3543824 • Letter: L

Question

long  factorial()   returns the factorial x! (x! = x(x-1)(x-2)(x-3)..(2)(1))

int fibonacci()    returns the Fibonacci fab(x) (fab(x)=fab(x-1)+fab(x-2); fab(0)=0; fab(1)=1)

double pow(int n)    returns x to the power n

void setX(int x) sets the value of x

int getX() returns the value of x

Write a test class MyMathTest to demonstrate the class MyMath. The test class must ask the user for an integer number and use the methods of MyMath to calculate the factorial, Fibonacci and Exponential. Then the test class should provide the given output, any display of x value should be done using function getX().

Sample Run:

Please enter a value for x: 5

1.  Factorial

2.  Fibonacci

3.  Power

4.  Change x

Please choose (-1 to stop): 1

The factorial of 5 is 120

Please choose (-1 to stop): 2

The Fibonacci of 5 is 8

Please choose (-1 to stop): 3

Please choose a value of n: 4

5 to the power 4 is 625

Please choose (-1 to stop): 4

Please enter new value for x: 4

Please choose (-1 to stop): -1

Thank you!!

Explanation / Answer

import java.util.*;

public class MyMathTest
{
private int x;
public MyMathTest(int k)
{
setX(k);
}
public MyMathTest()
{
x =0;
}
long factorial()
{
long n=1;
for(int i=1; i<=x; i++)
n = n*i;
return n;
}
int fibonacci()
{
int[] fib = new int[x+2];
fib[0] = 0;
fib[1] = 1;
for(int i=2; i<=x+1; i++)
fib[i] = fib[i-1]+ fib[i-2];
return fib[x+1];
}
double pow(int n)//
{
double ans =1;
for(int i=0; i<n; i++)
ans = ans*x;
return ans;
}
void setX(int x)
{
if(x<0) this.x= 0;
this.x = x;
}
int getX()
{
return x;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int k = 0;
System.out.println("Please enter a value for x: ");
k = in.nextInt();
int choice = 0;
MyMathTest MMT = new MyMathTest(k);
System.out.println("1.Factorial");
System.out.println("2.Fibonacci");
System.out.println("3.Power");
System.out.println("4.Change x");
while(choice!=-1)
{
System.out.println("Please choose (-1 to stop): ");
choice = in.nextInt();
if(choice==-1) break;
switch(choice)
{
case 1: System.out.println("The factorial of "+ MMT.getX() + " is " + MMT.factorial()); break;
case 2: System.out.println("The Fibonacci of "+MMT.getX() + " is " + MMT.fibonacci()); break;
case 3:
{
System.out.println("Please choose a value of n: ");
int n =in.nextInt();
System.out.println(""+MMT.getX() +" to the power " + n + " is " + MMT.pow(n));
}
break;
case 4:
{
System.out.println("Please enter new value for x: ");
int n =in.nextInt();
MMT.setX(n);
} break;
default:break;
}
}
System.out.println("Thank you!! ");
} // end main
} //end class