Korean English Japanese Chinese (Simplified) Chinese (Traditional)

 

 

 

 

 

2018번: 수들의 합 5

어떠한 자연수 N은, 몇 개의 연속된 자연수의 합으로 나타낼 수 있다. 당신은 어떤 자연수 N(1 ≤ N ≤ 10,000,000)에 대해서, 이 N을 몇 개의 연속된 자연수의 합으로 나타내는 가지수를 알고 싶어한

www.acmicpc.net

 

 

 

 

난이도: 실버 5

풀이: 투 포인터 알고리즘을 적용하여, sum < N일 때, sum > N일 때, 그리고 sum == N 일 때의 활동을 잘 궁리해야 하는 문제이다. sum == N일 때 start ++;을 채택하여 코드를 짰더니, end가 6일 때 더 이상 나아가지 않는 문제가 발생하여 15를 넣으면 2가 나왔다.

 

 

 

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
32
package Silver;
 
import java.io.*;
import java.util.*;
 
public class Q2018 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        int N                 =    scanner.nextInt();
        int count            = 1;
        int start_index    = 1;
        int end_index    = 1;
        int sum                = 1;
        
        while (end_index != N) {
            if (sum == N) {
                count ++;
                end_index ++;
                sum = sum + end_index;
            } else if (sum > N) {
                sum = sum - start_index;
                start_index ++;
            } else {
                end_index ++;
                sum = sum + end_index;
            }
        }
        
        System.out.println(count);
    }
}
cs

 

 

If you like this post, please give me a ❤️...!
 
✰Popular Posts✰
✰Recent Posts✰
 

❤ from Seoul, Daejeon, Tokyo, Fukuoka