백준

1789번: 수들의 합

bingual 2022. 2. 16. 10:12
반응형

 

 

 

 

 

 

풀이

 

1 ~ 19까지의 사이값을 전부 더하면 190이 나온다. 즉 200은 19개까지의 중복되지않은 자연수를 가질 수 있으므로 200을 초과한다면 cnt에서 -1을 해주면 된다.

 

결과값은 2^31-1을 초과할수 있으니 정수형 long을 사용해야한다.

 

 

 

 

 

자바

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

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

		long s = Long.parseLong((br.readLine()));
		br.close();
		
		long sum = 0;
		int cnt = 0;
		while (s >= sum) {
			sum += (++cnt);
		}
		System.out.print(cnt - 1);
	}
}

 

 

 

 

 

 

파이썬

s = int(input())

sum = 0
cnt = 0
while s >= sum:
    cnt += 1
    sum += cnt
  
print(cnt - 1)