프로그래밍 공부

피타고라스 정리를 만족하는 수 구하기(직각삼각형 찾기) 본문

CS/Algorithm

피타고라스 정리를 만족하는 수 구하기(직각삼각형 찾기)

khj1999 2021. 8. 4. 13:29

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중포문의 차이는 엄청난걸 알 수가 있다.

Comments