C++ 에서
cmath
라이브러리 써보기
정수 M부터 N까지 중 완전 제곱수 (Ex. 1, 4(22), 9(32), 16, ... ) 를 찾아서 최솟값과 완전 제곱수의 합을 출력하는 간단한 연습문제였는데..
왜 C++ 코드는 실패하고, Python 코드는 되는 것인가 ㅠ
변수 초기화: 정적(static) 변수와 전역(global) 변수의 경우 초기화하지 않아도 0으로 정의되지만 아래와 같은 지역변수(local)는 초기화하지 않을 경우 이상한 값이 저장될 수 있다.
int g; // 전역변수
int main(){
static int s; // 정적변수
int l; // 지역변수
printf("global : %d, static: %d, local : %d", g, s, l);
}
global : 0, static: 0, local : 4194432
아래와 같이 컴파일러에 따라서 지역변수의 경우도 0으로 초기화하는 경우가 있다고 한다. 내가 백준 풀이를 위해 사용한 온라인컴파일러 는 지역변수를 0으로 초기화해서 반례가 없는 것처럼 보였으나, 백준 정답확인을 위해 사용하는 컴파일러는 지역변수를 0으로 초기화하지 않기 때문에 계속 오답이 나왔다.
However, in practice, many C++ compilers choose to initialize local variables to zero by default for efficiency reasons. When a new variable is allocated on the stack, the compiler can simply set its memory to zero rather than leaving it uninitialized, which can help avoid potential bugs caused by uninitialized memory.
// 이 코드가 4%에서 계속 틀렸습니다가 뜬다.. 디버깅을 해보도록 하자!
#include <iostream>
#include<cmath>
using namespace std;
int main(){
// int M,N,a,tot,min;
int M,N,a,tot=0,min; // 위와 같이 tot을 초기화하면 문제가 해결된다...
cin >> M >> N;
a = static_cast<int>(sqrt(M));
if (a < sqrt(M))
a++;
if (pow(a,2) > N){
cout << -1;
return 0;
}
min=pow(a,2);
while(pow(a,2)<=N) {
tot+=pow(a,2);
a++;
}
cout << tot << endl << min;
}
위 로직 그대로 파이썬으로 옮겨 보았다.
M,N=map(int,open(0).read().split()) a=int(M**0.5) if a**2 < M: a+=1 if a**2 > N: print(-1) else: tot = 0 mn = a**2 while(a**2<=N): tot += a**2 a+=1 print(tot) print(mn)
신기하게도 정답이 떴다..