자바로 백준 1789 풀기

hong030·2023년 4월 5일
0
  • 실버 5단계 문제

풀이)

서로 다른 N개의 자연수의 합이 S일 때, S가 주어질 경우 N의 최대 개수를 구하여라.

어려운 문제는 아니지만 연산 속도를 줄이는 것에 주의해야 한다.
N >= 1 + 2 + ... n인 n을 찾으면 된다.

이 때, N >= n*(n+1)/2 공식을 써서 곱셈 연산을 하면 시간이 초과된다.

for문을 돌려 그냥 1개씩 더하는 게 낫다.

실제로 곱셈을 통해 연산한 경우 덧셈으로 연산한 것보다 속도가 10배 이상 느리다.

내 코드)*

import java.io.*;

public class Main {
	public static void main(String[]args) throws IOException{		
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));		
		long N = Long.parseLong(bf.readLine());
		
		int ans = 1;
		long num = 0;
		
		if(N==1 || N==2) {
			System.out.println(1);
			return;
		}
		/*
		while(true) {
			num = ans*(ans+1)/2;
			if(N<num) {
				System.out.println(ans-1);
				break;
			}else if (N==num) {
				System.out.println(ans);
				break;
			}
			ans++;
		}
		*/

		while(true) {
			num += ans;
			if(N<num) {
				System.out.println(ans-1);
				break;
			}else if (N==num) {
				System.out.println(ans);
				break;
			}
			ans++;
		}
		
	}
}

profile
자바 주력, 프론트 공부 중인 초보 개발자. / https://github.com/hongjaewonP

0개의 댓글