Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
Tags
- Stack
- bit manipulation
- Counting
- 코딩테스트
- database
- Class
- greedy
- string
- Method
- Matrix
- Math
- dynamic programming
- hash table
- 파이썬
- geometry
- java
- Binary Tree
- Binary Search
- 구현
- sorting
- implement
- Tree
- array
- SQL
- 코테
- simulation
- two pointers
- Number Theory
- Data Structure
- 자바
Archives
- Today
- Total
코린이의 소소한 공부노트
[프로그래머스/Lv.1] 악수의 개수와 덧셈 본문
1. Input
1) int 변수 left
2) int 변수 right
2. Output
1) left부터 right까지의 모든 수들 중에서, 약수의 개수가 짝수인 수는 더하고, 약수의 개수가 홀수인 수는 뺀 수
3. Constraint
1) 1 ≤ left ≤ right ≤ 1,000
4. Example
Input: left=13, right=17 -> Output: 43
설명: 13, 14, 15, 16, 17은 약수의 개수가
각각 2, 4, 4, 5, 2개이므로 약수의 개수가 홀수 개인 16만 빼고 나머지는 더하면 된다 -> 13+14+15-16+17=43
5. Code
1) 첫 코드(2022/??)
int answer = 0;
if(1<=left && left<=right && right<=1000){
// 약수 개수 확인 후 더할지 뺄지 결정하는 for문
for(int i=left ; i<=right ; i++){
if( test(i)%2 == 0) { answer += i; }
else { answer -= i; }
} // for
}
return answer;
// 약수 개수 확인하는 메서드
int test(int n){
int count=1; // 1은 무조건 약수
if(n>=2){
for(int i=2 ; i<=n ; i++)
if(n%i == 0) count++;
}
return count;
2) 수학 지식을 이용해 성능을 높인 코드(2022/11/14)
int sum = 0;
for(int n=left ; n<=right ; n++){
// 제곱수는 약수의 개수가 홀수, 나머지는 짝수
int j=1, sign=1;
while(j<=n){
if(Math.pow(j,2)==n){
sign = -1; break; }
else if(Math.pow(j,2)>n)
break;
j++;
} // while
sum += sign * n;
} // for
return sum;
'코딩테스트 풀이 > JAVA' 카테고리의 다른 글
[프로그래머스/Lv.1] 음양 더하기 (0) | 2022.11.15 |
---|---|
[프로그래머스/Lv.1] 로또의 최고 순위와 최저 순위 (0) | 2022.11.15 |
[프로그래머스/Lv.1] 숫자 문자열과 영단어 (0) | 2022.11.14 |
[프로그래머스/Lv.1] 부족한 금액 계산하기 (0) | 2022.11.11 |
[프로그래머스/Lv.1] 없는 숫자 더하기 (0) | 2022.11.11 |