- フィボナッチ数列の第n項を計算する
以下は反復処理を使用したフィボナッチ数列の計算方法です。再帰処理に比べて効率が向上しています。
public class Fibonacci {
public static int calculate(int term) {
int prev = 0, current = 1;
for (int i = 2; i <= term; i++) {
int next = prev + current;
prev = current;
current = next;
}
return term == 0 ? 0 : current;
}
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("何番目の項を出力しますか? ");
int n = input.nextInt();
System.out.println("結果: " + calculate(n));
}
}
- 1! + 2! + ... + 10! を計算する
階乗の計算をループで実行し、合計値を求める方法です。
public class FactorialSum {
public static void main(String[] args) {
long total = 0;
for (int i = 1; i <= 10; i++) {
long factorial = 1;
for (int j = 1; j <= i; j++) {
factorial *= j;
}
total += factorial;
}
System.out.println("1!+2!+...+10! = " + total);
}
}
- 3桁のアームストロング数を判定する
各桁の立方和が元の数と一致するかを確認します。
import java.util.Scanner;
public class ArmstrongChecker {
public static boolean isArmstrong(int number) {
int original = number;
int sum = 0;
while (number > 0) {
int digit = number % 10;
sum += digit * digit * digit;
number /= 10;
}
return sum == original;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("3桁の数を入力: ");
int input = scanner.nextInt();
if (isArmstrong(input)) {
System.out.println(input + "はアームストロング数です");
} else {
System.out.println(input + "はアームストロング数ではありません");
}
}
}
- 二次方程式 ax² + bx + c = 0 の解を求める
判別式に基づいて解の種類を判定し、実数解を計算します。
public class QuadraticEquation {
public static void solve(double a, double b, double c) {
double discriminant = b * b - 4 * a * c;
if (discriminant < 0) {
System.out.println("実数解は存在しません");
return;
}
double sqrtD = Math.sqrt(discriminant);
double root1 = (-b + sqrtD) / (2 * a);
double root2 = (-b - sqrtD) / (2 * a);
System.out.println("解: x1 = " + root1 + ", x2 = " + root2);
}
public static void main(String[] args) {
solve(1.0, -3.0, 2.0);
}
}