Post

Math_몫과 나머지 사용해서 연속된 자연수의 합 구하기

✅ n이라는 자연수가 주어졌을 때 연속된 자연수의 합으로 n이 구해지는 경우의 수

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
class Main {

    public int solution(int n){
    int answer= 0;
    int howManyContinuousNum=1;
    n--;
    while(n>0){
        howManyContinuousNum++;
        n= n-howManyContinuousNum;
        if( n % howManyContinuousNum ==0) answer++;
    }

    return answer;
}
    public static void main(String[] args) {
        Main T = new Main();
        Scanner sc= new Scanner(System.in);
        int n = sc.nextInt();
        System.out.print(T.solution(n));
    }
}

//⭐️input:
//15
//⭐️output:
//3

🔵 ThingsILearned

코딩공책-36

  1. 녹색 방법이 위 코드, 노란색 방법이 아래 코드
  2. 녹색 방법으로 풀면 1부터 i까지 자연수의 합을 구할 필요가 없다는 장점이 있다.
  3. 또 1부터 i까지 자연수의 합이 n보다 커지는 경우도 방지할 수 있다. n에서 1부터 i까지의 합을 게속 빼버리고 있기 때문에 0보다 크도록 만들면 끝.

🟢 1부터 n까지 합을 구해서 푸는 방법

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Main {

    public int solution(int n){
    int answer= 0;
    for(int i=2; i<n; i++){
        int sum= (i* (i+1)) / 2;
        if(sum > n) break;
        int divide= (n - sum) % i;
        if(divide ==0) answer++;
    }

    return answer;
}
    public static void main(String[] args) {
        Main T = new Main();
        Scanner sc= new Scanner(System.in);
        int n = sc.nextInt();
        System.out.print(T.solution(n));
    }
}

🟢 Two Pointer로 푸는 방법

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
33
class Main {

    public int solution(int n){
    int answer= 0;
    int lt=1;
    int sum=lt;
    int rt=lt+1;
    while(lt<n/2+2 && rt<n){
        sum +=rt;
        if(sum<n){
            rt++;
        }else if(sum>n){
            lt++;
            rt=lt+1;
            sum=0;
        }else if(sum==n){
            answer++;
            lt++;
            rt=lt+1;
            sum=0;
        }
    }

    return answer;
}
    public static void main(String[] args) {
        Main T = new Main();
        Scanner sc= new Scanner(System.in);
        int n = sc.nextInt();
        System.out.print(T.solution(n));
    }
}

This post is licensed under CC BY 4.0 by the author.