[JAVA] 백준 2018: 수들의 합 5

바위너구리·2023년 1월 3일
0

백준 풀이🐬

목록 보기
14/17
post-thumbnail

문제

실버 5
https://www.acmicpc.net/problem/2018

풀이

package Baekjoon;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class S5_2018 {

  public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer st = new StringTokenizer(br.readLine());

    int n = Integer.parseInt(st.nextToken());
    int start = 1;
    int end = 2;
    int sum;
    int answer = 1;

    while (start < n / 2 + 1) {
      sum = (start + end) * (end - start + 1) / 2;

      if (sum < n) {
        end++;
      }
      else if (sum == n) {
        answer++;
        start++;
        end = start + 1;
      }
      else {
        start++;
        end = start + 1;
      }
    }

    System.out.println(answer);
  }

}

등차수열의 합

(start + end) * (end - start + 1) / 2

[Do it! 알고리즘 코딩테스트 자바편]

과정

1. 문제 분석 & 풀어보기

  • 나타내는 방법에 숫자 그대로도 있기 때문에 count를 1로 초기화
  • start_index를 오른쪽으로 한 칸 이동 == 연속된 자연수에서 왼쪽 값 삭제
  • end_index를 오른쪽으로 한 칸 이동 == 연속된 자연수의 범위 한 칸 더 확장

2. 슈도코드

3. 코드

    Scanner sc = new Scanner(System.in);
    int n = sc.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 += end_index;
      } else if (sum > n) {
        sum -= start_index;
        start_index++;
      } else {
        end_index++;
        sum += end_index;
      }
    }
    System.out.println(count);

0개의 댓글