#1. factorial 메서드를 재귀 메서드 호출 사용하지 말고 작성
#2. gcd메서드를 재귀 메서드 호출 하지 말고 작성
#3. 배열 a의 모든 요소의 최대공약수를 구하는 메서드 작성
package algo;
public class jdfslka {
public static int factorial(int i) {
if (i==1) {
return i;
} else {
return i * (factorial(i-1));
}
}
public static int norecurseFact(int i ) {
int rst = 1;
for(int k = i; k>0; k--) {
rst *= k;
}
return rst;
}
public static int gcd(int x, int y) {
if(x<y) {
int temp = x;
x = y;
y = temp;
}
int a = x;
int b = y;
int remain = a%b;
while(remain != 1) {
if(remain == 0) {
return b;
}else {
a = b;
b = remain;
remain = a%b;
}
}
return 1;
}
public static int gcdArray(int[] arr) {
int curr = gcd(arr[0], arr[1]);
int sm = arr[1];
for(int i = 2; i<arr.length; i++) {
if(curr == 1) {
break;
}
curr = gcd(curr, arr[i]);
}
return curr;
}
public static void main(String args[]) {
System.out.println(factorial(4));
System.out.println(factorial(5));
System.out.println(gcd(54,69));
int[] arr = {54,36,18,90};
System.out.println(gcdArray(arr));
}
}
728x90
'자료구조당' 카테고리의 다른 글
알고리즘의 성능 분석 (1) | 2023.11.14 |
---|---|
자료구조와 알고리즘 (0) | 2023.11.14 |
Do it! 자료구조와 함께 배우는 알고리즘 입문 : Comparator, Generics (8) | 2023.05.23 |
doit (0) | 2023.05.13 |
Do it! 자료구조와 함께 배우는 알고리즘 입문 - 자바 편 (p.111~115) [ 검색 알고리즘 ] (0) | 2023.05.11 |