ホームページ  >  記事  >  Java  >  Javaの階乗

Javaの階乗

王林
王林オリジナル
2024-08-30 16:25:37852ブラウズ

この記事では、階乗計算を目的として Java プログラミング言語でコードを記述するさまざまな方法について学びます。使いやすいオブジェクト指向言語の 1 つである Java は、プラットフォームに依存せず、シンプルなプログラミング言語です。 Java のコンパイラとインタプリタは、セキュリティを主要な側面として開発されました。 Javaにはさまざまな応用範囲があります。

広告 このカテゴリーの人気コース JAVA マスタリー - スペシャライゼーション | 78 コース シリーズ | 15 回の模擬テスト

無料ソフトウェア開発コースを始めましょう

Web 開発、プログラミング言語、ソフトウェア テスト、その他

階乗、「!」で記号化(感嘆符) は、数値とそれより小さいすべての数値を乗算する数学演算です。たとえば、数値が 5 の場合、階乗の出力は 5 になります。 = 5*4*3*2*1 = 120.

Java プログラムを実行するには?

1.コードを完成させ、(ファイル名).java

として保存します。

2.ターミナルを開き、次の Java コマンドを実行します。

  • a. javac (ファイル名).java

3.上記のコマンドはクラス ファイルを生成します。

4.次に、クラスファイルを実行します。

  • a. java (ファイル名)

さまざまな手法を使用した階乗の例

以下は、さまざまなメソッドを使用したさまざまな例です:

例 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 拡張子を付けて保存します。

コードの説明:

これは、値 1 の 2 つの変数「i」と「fact」で始まり、次に階乗を計算するための数値である 5 の「number」で始まりました。 For ループに入り、数値 (5) と一致するまで i の値を増やし続けました。増加中、ファクトの値が増加するたびに乗算され、ファクトに新しい値が割り当てられます。

出力:

Javaの階乗

例 2 – ユーザー入力の使用

もう 1 つの一般的に使用される方法は、計算のために数値を事前に定義するのではなく、ユーザーの入力を求める方法です。

ユーザー入力ベースの計算については、以下のコードを参照してください:

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 より大きい数値を入力してください:」というプロンプトが表示されます。これは、階乗を計算できないことは明らかです。負の数について計算されます。これで、正の数が受け入れられ、階乗の計算が続行され、以下の画像に示すように出力が印刷されます。

出力:

Javaの階乗

例 3 – 再帰メソッドの使用

再帰は、プログラミングの世界で最も便利なツールの 1 つです。再帰とは基本的に関数を再利用することを意味します。いわば、ここでは余分な数の変数を定義する必要はありません。つまり、変数は 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:

Javaの階乗

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.

以上がJavaの階乗の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。