Monday 19 June 2017

Java Code to compute the xn(x power n)/n!

Problem:

For a given x and a given n, design an algorithm to compute xn (x power n)/n!.

Solution:

package com.myprograms;

import java.util.Scanner;

public class FactorialComputation2 {

int n;

int x;

int product = 1;

double xPowerN;

public static void main(String[] args) {

FactorialComputation2 factorialComputation2 = new FactorialComputation2();
factorialComputation2.getTheValues();
factorialComputation2.findXPowerN();
factorialComputation2.findFactorial();
factorialComputation2.printTheResult();

}

private void getTheValues(){
Scanner s = new Scanner(System.in);
System.out.println("enter how many numbers you want to do factorial");
n = s.nextInt();
System.out.println("enter x value");
x = s.nextInt();
s.close();
}

private void findFactorial(){
for(int i = 1; i <=n; i++){
product = product * i;
}
}

private void findXPowerN(){
xPowerN = Math.pow(x, n);
}

private void printTheResult(){
System.out.println("the result is: "+ xPowerN/product);
}
}


Output:

enter how many numbers you want to do factorial
5
enter x value
2
the result is: 0.26666666666666666


No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...