반응형
# 자바 (java) 팩토리얼
1. 팩토리얼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
import java.util.Scanner;
// factorial of input integer
public class FactorialTest {
public static void main(String[] args) {
int n, fact = 1;
int first = 0;
Scanner input = new Scanner(System.in);
System.out.print("Input an integer: ");
n = input.nextInt();
first = n;
while (n > 0) {
fact = fact * n;
n = n - 1;
}
System.out.println("factorial of input number " + first + " is " + fact);
input.close();
}
}
|
cs |
2. 자바 팩토리얼 클래스
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
import java.util.Scanner;
// factorial of input integer using class
class Factorial {
int fact = 1;
public int factorialTest(int num) {
while (num > 0) {
fact = fact * num;
num = num - 1;
}
return fact;
}
}
public class FactorialTest {
public static void main(String[] args) {
int num;
Scanner input = new Scanner(System.in);
System.out.print("Input an integer: ");
num = input.nextInt();
input.close();
Factorial fact = new Factorial();
int result = fact.factorialTest(num);
System.out.println("factorial of input number " + num + " is " + result);
}
}
|
cs |
3. 자바 팩토리얼 재귀호출
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
import java.util.Scanner;
// factorial (recursive)
class FactorialRecursive {
int fact = 1;
public int factorial(int num) {
return (num > 0) ? num * factorial(num - 1) : 1;
}
}
public class FactorialTest {
public static void main(String[] args) {
int num;
Scanner input = new Scanner(System.in);
input.close();
num = input.nextInt();
FactorialRecursive factorialRecursive = new FactorialRecursive();
int result = factorialRecursive.factorial(num);
System.out.println("factorial of input number " + num + " is " + result);
}
}
|
cs |
반응형
'JAVA 자바 > JAVA 실습_기초' 카테고리의 다른 글
[JAVA #12] 자바 입력한 두 숫자의 최대공약수 (0) | 2020.05.01 |
---|---|
[JAVA #11] 자바 10이하 정수의 짝수의 합 (0) | 2020.05.01 |
[JAVA #9] 자바 배열 출력 (0) | 2020.04.27 |
[JAVA #8] 입력받은 배열의 최소값 (0) | 2020.04.27 |
[JAVA #7] 배열의 최소값 (0) | 2020.04.27 |