알고리즘/SWEA
6782. 현주가 좋아하는 제곱근 놀이
병인
2019. 10. 15. 11:17
SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
처음에 입력 값을 안 보고 풀어서 int로 했다가 낭패를 봤다.
<JAVA>
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Solution {
public static void main(String[] args) throws Exception {
int T, cnt;
long N, temp;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
T = Integer.parseInt(br.readLine());
for (int t = 1; t <= T; ++t) {
cnt = 0;
N = Long.parseLong(br.readLine());
while (true) {
if (N == 2)
break;
else if (N == 1) // N이 1이면 1 증가 후 종료
{
cnt += 1;
break;
} else {
temp = (long) (Math.sqrt(N));
if (temp * temp == N) {
++cnt;
N = temp;
} else {
cnt += ((temp + 1) * (temp + 1) - N);
++cnt;
N = temp + 1;
}
}
}
System.out.println("#" + t + " " + cnt);
}
}
}
<C++>
#include <iostream>
#include<cmath>
using namespace std;
int main()
{
ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
int T, cnt;
long N, temp;
cin >> T;
for (int t = 1; t <= T; ++t)
{
cnt = 0;
cin >> N;
while (true)
{
if (N == 2)
break;
else if (N == 1) // N이 1이면 1 증가 후 종료
{
cnt += 1;
break;
}
else
{
temp = long(sqrt(N));
if (pow(temp, 2) == N)
{
++cnt;
N = long(sqrt(N));
}
else
{
cnt += (pow(temp + 1, 2) - N);
++cnt;
N = long(sqrt(N)) + 1;
}
}
}
cout << "#" << t << " " << cnt << "\n";
}
return 0;
}