프로그래밍 공부
피타고라스 정리를 만족하는 수 구하기(직각삼각형 찾기) 본문
x^2 + y^2 = z^2을 만족하는 수를 찾으면 된다.
코드
#include <bits/stdc++.h>
#include <ctime>
using namespace std;
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int cnt = 0;
clock_t start, end;
start = clock();
for(int i = 1; i <= 1000; i++){
for(int j = i; j <= 1000; j++){
int z = sqrt(i * i + j * j);
if(i*i + j*j == z*z && z <= 1000){
cnt++;
//cout << i << " + " << j << " = " << z << '\n';
}
}
}
cout << cnt << '\n';
end = clock();
double time = double(end - start) / CLOCKS_PER_SEC;
cout << "2 - for time : " << time << "sec" << '\n'; // 2중 포문 걸린 시간
cnt = 0;
start = clock();
for(int z = 1; z <= 1000; z++){
for(int x = 1; x <= 1000; x++){
for(int y = x; y <= 1000; y++){
if(x*x + y*y == z*z){
cnt++;
//cout << x << " + " << y << " = " << z << '\n';
}
}
}
}
cout << cnt << '\n';
end = clock();
time = double(end - start) / CLOCKS_PER_SEC;
cout << "3 - for time : " << time << "sec" << '\n'; // 3중 포문 걸린시간
return 0;
}
결과
3중포문과 2중포문의 차이는 엄청난걸 알 수가 있다.
'CS > Algorithm' 카테고리의 다른 글
Kadane's Algorithm(카데인 알고리즘) (0) | 2024.10.17 |
---|---|
Sort/정렬 - Quick Sort/퀵 정렬 (0) | 2021.07.26 |
Sort/정렬 - Insertion Sort/삽입 정렬 (0) | 2021.07.19 |
Sort/정렬 - Selection Sort/선택 정렬 (0) | 2021.07.13 |
Sort/정렬 - Bubble Sort/거품 정렬 (0) | 2021.07.13 |
Comments