[Programmers] 약수의 합 - 연습문제

동민·2021년 3월 10일
// 약수의 합 - 연습문제
public class SumOfAliquot {

	public int solution1(int n) {
		int answer = 0;
		for (int i = 1; i <= n / 2; i++) { // 약수는 n 까지 모두 비교할 필요 없이 절반까지만 비교하면 된다. 단 answer에 n을 더해주어야 함
			if (n % i == 0) {
				answer += i;
			}
		}
		return answer + n; // for문에서 n/2 까지만 비교했을 때 answer에 n을 더해주어야 한다.
	}

	public int solution(int n) {
		int answer = 0;
		for (int i = 1; i <= n; i++) {
			if (n % i == 0) {
				answer += i;
			}
		}
		return answer;
	}

	public static void main(String[] args) {

		SumOfAliquot s = new SumOfAliquot();
		System.out.println(s.solution(12));
		System.out.println(s.solution(5));

	}

}
profile
BE Developer

0개의 댓글