Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

재귀를 사용하여 숫자의 계승을 찾는 Java 프로그램

<시간/>

이 기사에서는 재귀를 사용하여 숫자의 계승을 찾는 방법을 이해할 것입니다. 숫자의 계승은 더 낮은 숫자 각각과의 곱입니다. 계승은 0보다 큰 자연수에 적용되는 함수입니다. 계승 함수의 기호는 다음과 같이 숫자 뒤의 느낌표입니다. 5!

재귀 함수는 특정 조건이 충족될 때까지 자신을 여러 번 호출하는 함수입니다. 재귀는 자기 유사 방식으로 항목을 반복하는 프로세스입니다. 프로그래밍 언어에서 프로그램이 동일한 함수 내에서 함수를 호출하도록 허용하는 경우 이를 함수의 재귀 호출이라고 합니다.

많은 프로그래밍 언어는 스택을 통해 재귀를 구현합니다. 일반적으로 함수(호출자)가 다른 함수(피호출자) 또는 자신을 피호출자로서 호출할 때마다 호출자 함수는 실행 제어를 피호출자에게 넘깁니다. 이 전송 프로세스에는 호출자에서 호출 수신자에게 전달할 일부 데이터가 포함될 수도 있습니다.

아래는 동일한 데모입니다 -

입력

입력이 -

라고 가정합니다.
Enter the number : 7

출력

원하는 출력은 -

The factorial of 7 is 5040

알고리즘

Step 1 - START
Step 2 - Declare an integer values namely ‘my_input’ and a long value namely ‘my_result’
Step 3 - Read the required values from the user/ define the values
Step 4 - A recursive function ‘factorial’ is defined which takes an integer as input and returns the product of the input and its previous number until the input value is reduced to 1.
Step 5 - The recursive function is called and the value ‘my_input’ is passed to it. Store the return value
Step 6 - Display the result
Step 7 - Stop

예시 1

여기에서 입력은 프롬프트에 따라 사용자가 입력하고 있습니다. 우리코딩 그라운드 도구에서 이 예제를 라이브로 사용해 볼 수 있습니다. 재귀를 사용하여 숫자의 계승을 찾는 Java 프로그램 .

import java.util.Scanner;
public class Factorial {
   public static void main(String[] args) {
      int my_input ;
      long my_result;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A reader object has been defined ");
      System.out.print("Enter the number : ");
      my_input = my_scanner.nextInt();
      my_result = factorial(my_input);
      System.out.println("The factorial of " + my_input + " is " + my_result);
   }
   public static long factorial(int my_input){
      if (my_input >= 1)
         return my_input * factorial(my_input - 1);
      else
         return 1;
   }
}

출력

Required packages have been imported
A reader object has been defined
Enter the number : 7
The factorial of 7 is 5040

예시 2

여기서 정수는 이전에 정의되었으며 그 값은 콘솔에 액세스되어 표시됩니다.

public class Factorial {
   public static void main(String[] args) {
      int my_input ;
      long my_result;
      my_input = 7;
      System.out.println("The number is defined as " +my_input);
      my_result = factorial(my_input);
      System.out.println("The factorial of " + my_input + " is " + my_result);
   }
   public static long factorial(int my_input){
      if (my_input >= 1)
         return my_input * factorial(my_input - 1);
      else
         return 1;
   }
}

출력

The number is defined as 7
The factorial of 7 is 5040