>  기사  >  Java  >  자바의 팩토리얼

자바의 팩토리얼

王林
王林원래의
2024-08-30 16:25:37852검색

이 글에서는 계승 계산을 위해 Java 프로그래밍 언어로 코드를 작성하는 다양한 방법에 대해 알아봅니다. 사용하기 쉬운 객체 지향 언어 중 하나인 Java는 플랫폼 독립적이며 간단한 프로그래밍 언어입니다. Java의 컴파일러와 인터프리터는 보안을 주요 측면으로 두고 개발되었습니다. Java에는 다양한 응용프로그램이 있습니다.

광고 이 카테고리에서 인기 있는 강좌 JAVA MASTERY - 전문 분야 | 78 코스 시리즈 | 15가지 모의고사

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

“!”으로 상징되는 팩토리얼 (느낌표)는 숫자에 작은 숫자를 모두 곱하는 수학적 연산입니다. 예를 들어 숫자가 5인 경우 계승의 출력은 5입니다! = 5*4*3*2*1 = 120.

Java 프로그램을 어떻게 실행하나요?

1. 코드를 완성하고 (파일 이름).java

로 저장하세요.

2. 터미널을 열고 다음 java 명령을 실행하세요.

  • 아. javac(파일 이름).java

3. 위의 명령은 클래스 파일을 생성합니다.

4. 이제 클래스 파일을 실행해 보세요.

  • 아. java(파일 이름)

다양한 방법을 활용한 Factorial의 예

다음은 다양한 방법을 사용한 다양한 예입니다.

예시 1 – 기본 방법 사용

앞으로 이제 계승 계산을 위한 간단한 Java 프로그램을 작성하겠습니다.

public class Factorial
{
public static void main(String args[])
{int i, fact=1;
int number=5;
for(i=1;i<=number;i++)
{
fact=fact*i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}

위 코드를 파일 이름과 .java 확장자로 저장하세요.

코드 설명:

두 개의 변수인 "i"와 "fact"로 시작하여 값이 1이고, "number"에 계승을 계산하는 숫자인 5가 있습니다. For 루프에 들어가서 숫자(예: 5)와 일치할 때까지 i 값을 계속 늘렸습니다. 증가하는 동안 팩트 값이 증가할 때마다 곱해지고 팩트에 새 값이 할당됩니다.

출력:

자바의 팩토리얼

예 2 – 사용자 입력 사용

또 다른 일반적으로 사용되는 방법은 계산을 위해 미리 정의된 숫자 대신 사용자 입력 숫자를 요청하는 것입니다.

사용자 입력 기반 계산은 아래 코드를 참조하세요.

import java.util.Scanner;
class Facto{
public static void main(String args[]) {
int q, a, fact = 1;
System.out.println("Please Enter a number:");
Scanner in = new Scanner(System.in);
q = in.nextInt();
if ( q < 0 )
System.out.println("Please enter a number greater than 0:");
else {
for ( a = 1 ; a <= q ; a++ )
fact = fact*a;
System.out.println("Factorial of "+q+" is = "+fact);
}
}
}

이전 예시와 마찬가지로 위의 코드를 저장하세요.

코드 설명:

이전 예와 위 예의 주요 차이점은 사용자 입력입니다. 휴식도 마찬가지다. 코드는 계산할 숫자를 요청한 후 사용자가 입력한 숫자가 "-" 안에 있는 음수인 경우 "0보다 큰 숫자를 입력하십시오:"라는 메시지를 표시합니다. 이는 계승이 불가능하므로 명백합니다. 음수로 계산됩니다. 이제 양수를 받아들이고 계승 계산을 진행한 후 아래 이미지와 같이 출력을 인쇄합니다.

출력:

자바의 팩토리얼

예 3 – 재귀 방법 사용

재귀는 프로그래밍 세계에서 가장 유용한 도구 중 하나입니다. 재귀는 기본적으로 함수를 재사용하는 것을 의미합니다. 즉, 여기서는 추가로 변수 수를 정의할 필요가 없습니다. 즉, 변수는 2개 이하만 갖게 됩니다.

재귀를 구현하는 주요 이유는 코드 길이를 줄이고 프로그램의 시간 복잡도를 우아하게 줄이는 능력입니다. 재귀 방법은 장점이 있지만 장기적으로 큰 영향을 미칠 수 있는 몇 가지 단점이 있습니다.

단점

재귀의 단점:

  • 기본적으로 재귀 코드를 디버깅하고 오류가 있는 모든 단계를 추적하는 것은 상당히 어렵습니다.
  • 그 외에도 재귀는 스택을 사용하여 작업을 수행하고 새로운 재귀 호출로 스택을 계속 추가하므로 더 많은 메모리를 사용합니다.
  • 그리고 현명하게 구현하지 않으면 재귀 기능이 느려질 수 있습니다.
  • StackOverflowException: 스택의 과도한 사용으로 인해 재귀 메서드에서 이 예외가 발생하는 경우가 많습니다.

아래 코드를 참고하세요:

public class FactorialExample2 {
static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String[] args) {
System.out.println("Factorial of 5 is: "+factorial(5));
}
}

앞서 했던 것처럼 프로그램을 저장하고 컴파일하세요.

코드 설명:

The above code starts with a single int variable and checks if it is equal to 1; if yes, it returns one, as factorial for 1 is 1. If not equal to 1, it proceeds with the recursion function. Our int value, for example, is 5, so it’ll be like “5 * factorial(5-1)”, factorial is called here for the second time, which is another call. Then it returns again with a newer int value, which is 4, “4 * factorial(4-1)”, now it’ll be the third call to the recursion method. Now, the newer int value is 3, which means “3 * factorial(3-1)”, now it’ll be the fourth call, and the value will be 2, which means “2 * factorial(2-1)”. The int value will be one in the next recursive call, which will terminate the function here. While every call was made, its value was saved in a Stack, which is a LIFO method. So, for the final Output, the result will be “5*4*3*2*1 = 120.”

Compared to other methods, Recursion is quite difficult to understand and to implement, but if understood well and implemented wisely, it is a good tool.

Output:

자바의 팩토리얼

It is highly recommended to use Recursion only in the case where writing an iterative code can be quite complex.

Now that we have learned various methods for implementing Factorial Calculations in Java Let’s explore a Built-in function that does the same work in a single line.

Example 4 – Using built-in Function

*) IntMath

Understanding the need for arithmetic operations over a value, a few functions specific to certain value types were written, we will see the Integer type value in work.

IntMath is a class for arithmetic calculations on an int value. IntMath class comes with a range of arithmetic operations, including factorial.

Syntax:

factorial (int n)

Conclusion – Factorial in Java

We started with an introduction to java and how to run a java program. Then we learned about Factorial Calculation and various methods, including Recursion, to accomplish it.

Towards the end, we learned about IntMath; a Java Function primarily focused on Arithmetic operations. Java is a widely-used programming language; it comes with many features; in this article, we learned about Factorial Calculations in Java, which is a tiny aspect.

위 내용은 자바의 팩토리얼의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:Java의 숫자 패턴다음 기사:Java의 숫자 패턴