JAVA 알고리즘 연습문제
//팩토리얼 구하기 :4! =4*3*2*1
public static double factorial(int n) {
int result = 1;
for (int i = n; i >= 1; i--)
{
result *= i;
}
return result;
}
반복문을 1부터 정수 N 까지의 정수를 곱하는 값을 계산하고 최종적으로 값을 반환합니다 result 변수에 초
기값을 1로 설정해주고 반복문에서 i 변수의 값을 1 감소 시키면서 변수 result 에 곱해준다
//배수의 합
// int result = MyMath.hap(10,3):=>0+3+6+9
// int result = MyMath.hap(10,4):=>0+4+8
public static int hap(int n,int baesu) {
int sum = 0;
for (int i = baesu; i < n; i += baesu) {
sum += i;
}
return sum;
}
배수 에서 시작으로 n 이전까지 의 배수를 구해 sum 변수에 더해준다
//누적승 구하기: n s m승 구하기
//result = MyMath.pow(2,3); => 2*2*2
public static double pow(double n,int m) {
double result = 1;
for (int i = 0; i < m; i++) {
result *= n;
}
return result;
}
result 변수를 1로 초기화한후 m번 반복하면서 n을 result에 곱해준다