Find GCD of two numbers

KH·2023년 5월 19일
0

source: https://school.programmers.co.kr/learn/courses/30/lessons/120808
ref: https://www.programiz.com/java-programming/examples/hcf-gcd

class Solution {
    public int[] solution(int numer1, int denom1, int numer2, int denom2) {
        int[] answer = {0,0};
        
        int a = numer1*denom2 + numer2*denom1;
        int b = denom1*denom2;
        
        int gcd = 1;
        // 반복문에서 and조건 생각 못했음...
        for (int i = 1; i <= a && i <= b; ++i) {

          // check if i perfectly divides both n1 and n2
          if (a % i == 0 && b % i == 0)
            gcd = i;
        }
        
        answer[0] = a/gcd;
        answer[1] = b/gcd;
        return answer;
    }
}

gcd 구하는 방법을 떠올리지 못하여 다음과 같이 억지로 테스트 통과함...

        // for(int k=0;k<3;k++){
        //     for(int i =2; i<1000;i++){
        //         if(a%i==0 && b%i==0){
        //             a=a/i;
        //             b=b/i;
        //         }
        //     }
        // }
        // ...?
profile
What, How, Why

0개의 댓글

관련 채용 정보