풀이)
서로 다른 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++;
}
}
}