1. two pointers algorithm
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public int solution(int n) {
int answer = 0;
int sum = 0;
int lt=0;
int m = n/2+1;
int[] arr = new int[m];
for (int i = 0; i < m; i++) {
arr[i] = i+1; //index 0에 1 들어가고, index 1에 2 들어가고
}
//two pointers algorithm
for (int rt = 0; rt < m ; rt++) {
sum += arr[rt]; //lt부터 rt까지의 합
if (sum == n) {
answer ++;
}
while (sum >= n) {
sum -=arr[lt++];
if (sum == n) {
answer++;
}
}
}
return answer;
}
public static void main(String[] args){
Main T = new Main();
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
System.out.println(T.solution(n));
}
}
2. 수학적 방식(몫과 나머지)
연속된 2개의 숫자인 경우
변수에 1과 2 분배 후 15 - 1 - 2 = 12 해준 뒤 12를 2로 나눈다 -> 6 그 후 분배한 1, 2 에 6을 각각 더해주면 7,8이 나온다.
연속된 3개의 숫자인 경우
변수에 1, 2, 3 분배 후 15 - 1 - 2 - 3 = 9 해준 뒤 9/3 = 3이 되고 처음 분배 한 1, 2, 3에 3을 각각 더하면 4, 5, 6이 나온다.
연속된 4개의 숫자인 경우
15 - 1- 2 - 3 - 4 =5인데 5/4를 하게 되면 맞아 떨어지지 않으므로 없다.
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public int solution(int n) {
int answer=0, cnt =1; //cnt : 연속된 자연수의 개수
n--;
while (n > 0) {
cnt ++;
n = n-cnt;
if (n % cnt == 0) {
answer ++;
}
}
return answer;
}
public static void main(String[] args){
Main T = new Main();
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
System.out.println(T.solution(n));
}
}
'Algorithm > 문제' 카테고리의 다른 글
31. 학급 회장(해쉬) (0) | 2023.08.16 |
---|---|
30. 최대 길이 연속 부분 수열 (0) | 2023.08.10 |
28. 연속 부분 수열 (1) | 2023.07.25 |
27. 최대 매출 (0) | 2023.07.25 |
26. 공통 원소 구하기 (0) | 2023.07.24 |