/* 약수의 개수와 덧셈
* 두 정수 left와 right가 매개변수로 주어집니다.
* left부터 right까지의 모든 수들 중에서, 약수의 개수가 짝수인 수는 더하고,
* 약수의 개수가 홀수인 수는 뺀 수를 return 하도록 solution 함수를 완성해주세요.
*
* left right result
* 13 17 43 13 + 14 + 15 - 16 + 17 = 43
* 24 27 52 24 - 25 + 26 + 27 = 52
*/
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 | public class programmer_1_31 { static int a1 = 13; static int b1 = 17; static int a2 = 24; static int b2 = 27; public int getCnt(int n){ int cnt = 0; for(int i=1; i*i <= n; i++){ if(n%i == 0){ cnt++; if(i*i < n) cnt ++; } } return cnt; } public int solution(int left, int right) { int answer = 0; for(int i = left; i <= right; i++){ if(getCnt(i) % 2 == 0) answer += i; else answer -= i; } return answer; } public static void main(String args[]){ programmer_1_31 t = new programmer_1_31(); System.out.println("---------------------------------------"); System.out.println("result = " + t.solution(a1,b1)); System.out.println("---------------------------------------"); System.out.println("result2 = " + t.solution(a2,b2)); System.out.println("---------------------------------------"); } } | cs |
'프로그래머스 > lv1' 카테고리의 다른 글
부족한 금액 계산하기 (1) | 2022.12.19 |
---|---|
문자열 다루기 기본 (0) | 2022.12.19 |
문자열 내림차순으로 배치하기 (0) | 2022.12.19 |
내적 (0) | 2022.12.19 |
수박수박수박수박수박수? (0) | 2022.12.14 |