알고리즘
백준 수들의 합5 (JAVA)
박카스마시며코딩
2023. 12. 6. 17:02
https://www.acmicpc.net/problem/2018
2018번: 수들의 합 5
어떠한 자연수 N은, 몇 개의 연속된 자연수의 합으로 나타낼 수 있다. 당신은 어떤 자연수 N(1 ≤ N ≤ 10,000,000)에 대해서, 이 N을 몇 개의 연속된 자연수의 합으로 나타내는 가지수를 알고 싶어한
www.acmicpc.net
저는 투포인트를 통해 문제를 해결하였습니다.
투포인트로 해당 숫자 사이의 값의 합을 구하고 이 값이 n보다 크다면 시작값을 늘려 합을 줄이고, 작다면 끝 값을 늘려 합을 줄여 문제를 해결하였습니다.
package BOJ.twopoint;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.function.Function;
public class BOJ_2018_2 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Function<String,Integer> stoi = Integer::parseInt;
int n = stoi.apply(br.readLine());
int result = cal(n);
System.out.println(result);
}
private static int cal(int n) {
int start = 0;
int end = 0;
int sum = 0;
int cnt = 0;
while(true){
if(end > n){
break;
}
if(sum == n){
cnt++;
}
if(sum >= n){
sum -= ++start;
}else{
sum += ++end;
}
}
return cnt;
}
}