Solving a mathematical problem using Java. Let's consider finding the factorial of a given number N:
```java
import java.math.BigInteger;
public class Factorial {
public static BigInteger factorial(int N) {
BigInteger result = BigInteger.ONE;
for (int i = 1; i <= N; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
public static void main(String[] args) {
int N = 10;
BigInteger factorialN = factorial(N);
System.out.println("Factorial of " + N + " is: " + factorialN);
}
}
```
In this example, we use the `BigInteger` class from the `java.math` package to handle large numbers since factorials can grow rapidly. The `factorial` method takes an integer `N` as input and calculates the factorial using a loop. Finally, the `main` method demonstrates how to use the `factorial` method by calculating the factorial of 10 and printing the result.
This code will output:
```
Factorial of 10 is: 3628800
```
Note that the `BigInteger` class allows you to perform arithmetic operations on integers of any size, which is necessary when dealing with factorials of large numbers.
No comments:
Post a Comment