Computer >> Máy Tính >  >> Lập trình >> Java

Chương trình Java để tìm giai thừa của một số

Trong bài này, chúng ta sẽ hiểu cách tìm giai thừa của một số. Giai thừa của một số là tích của chính nó với mỗi số thấp hơn của nó.

Giai thừa là một hàm được áp dụng cho các số tự nhiên lớn hơn 0. Biểu tượng cho hàm giai thừa là một dấu chấm than sau một số, như sau:5!

Dưới đây là một minh chứng về điều tương tự -

Đầu vào

Giả sử đầu vào của chúng tôi là -

Enter the number : 5

Đầu ra

Đầu ra mong muốn sẽ là như sau, tức là 5! =5x4x3x2x1

The factorial of 5 is 120

Thuật toán

Step1- Start
Step 2- Declare three integers: my_input_1, factorial and i
Step 3- Prompt the user to enter an integer value/ Hardcode the integer
Step 4- Read the values
Step 5- Run while loop, multiply the number with its lower number and run the loop till the
number is reduced to 1.
Step 6- Display the result
Step 7- Stop

Ví dụ 1

Ở đây, đầu vào đang được người dùng nhập dựa trên lời nhắc. Bạn có thể thử trực tiếp ví dụ này trong công cụ nền tảng mã hóa của chúng tôi Chương trình Java để tìm giai thừa của một số .

import java.util.Scanner;
public class FindFactorial{
   public static void main(String arg[]){
      int my_input, factorial, i;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A scanner object has been defined ");
      System.out.println("Enter a number: ");
      my_input = my_scanner.nextInt();
      factorial=1;
      for(i=1;i<=my_input;i++){
         factorial=factorial*i;
      }
      System.out.printf("The factoral of %d is %d" , my_input,factorial);
   }
}

Đầu ra

Required packages have been imported
A scanner object has been defined
Enter a number:
5
The factorial of 5 is 120

Ví dụ 2

Ở đây, số nguyên đã được xác định trước đó và giá trị của nó được truy cập và hiển thị trên bảng điều khiển

public class FindFactorial{
   public static void main(String arg[]){
      int my_input, factorial, i;
      my_input = 5;
      System.out.printf("The number is %d ",my_input );
      factorial=1;
      for(i=1;i<=my_input;i++){
         factorial=factorial*i;
      }
      System.out.printf("\nThe factorial of %d is %d" , my_input,factorial);
   }
}

Đầu ra

The number is 5
The factorial of 5 is 120