[ BASIC MATH ] 05. 점화식과 재귀함수 with java
📚 Table of Contents
개념
피보나치 수열
public class Main {
// 재귀함수
static int recursion(int n) {
if (n < 3) {
return 1;
}
return recursion(n - 2) + recursion(n -1);
}
public static void main(String[] args) {
// 반복문
if (n <= 2) {
result = 1;
} else {
for (int i = 2; i < n; i++) {
result = a1 + a2;
a1 = a2;
a2 = result;
}
}
System.out.println(result); // 8
System.out.println(recursion(n)); // 8
}
}
팩토리얼
public class Main {
// 재귀함수
static int factorial(int n) {
if (n == 1) {
return 1;
}
return n * factorial(n - 1);
}
public static void main(String[] args) {
System.out.println(factorial(1)); // 1
System.out.println(factorial(2)); // 2
System.out.println(factorial(3)); // 6
System.out.println(factorial(4)); // 24
System.out.println(factorial(5)); // 120
}
'Knowledge > 기초수학' 카테고리의 다른 글
[ BASIC MATH ] 06. 지수(Exponents)와 로그 (logarithms) with java (0) | 2023.11.28 |
---|---|
[ BASIC MATH ] 06. 지수(Exponents)와 로그 (logarithms) (0) | 2023.11.28 |
[ BASIC MATH ] 05. 점화식과 재귀함수 (0) | 2023.11.28 |
[ BASIC MATH ] 04. 조합 ( Combination ) (2) | 2023.11.28 |
[ BASIC MATH ] 03. 순열 ( permutation ) _ with java (1) | 2023.11.22 |