기본 콘텐츠로 건너뛰기

프로그래머스 - N개의 최소공배수

2개의 값에 대하여 gcd를 이용해 lcm을 구하는 것을 N개에 대해 반복함
public class NLCM {
    public long gcd(long a,long b) {
        if(a==0)
            return b;
        else
            return gcd(b%a,a);      
    }
    public long lcm(long a,long b) {
        return a*b/gcd(a,b);        
    }   

    public long nlcm(int[] num) {
        long answer=num[0];
        for(int i=0;i<num.length-1;i++) {
            answer = lcm(answer,num[i+1]);
        }
        return answer;
    }

    public static void main(String[] args) {
        NLCM c = new NLCM();
        int[] ex = { 2, 6, 8, 14 };
        // 아래는 테스트로 출력해 보기 위한 코드입니다.
        System.out.println(c.nlcm(ex));
    }
}

댓글

이 블로그의 인기 게시물

프로그래머스 - 시저 암호

public class Caesar { String caesar ( String s , int n ) { n %= 26 ; String result = "" ; char [] temp = s . toCharArray (); for ( int i = 0 ; i < temp . length ; i ++) { if ( temp [ i ]>= 'a' && temp [ i ]<= 'z' ) temp [ i ] = ( char ) (( temp [ i ]+ n )> 'z' ? ( temp [ i ]+ n - 1 )% 'z' + 'a' : ( temp [ i ]+ n )); else if ( temp [ i ]>= 'A' && temp [ i ]<= 'Z' ) temp [ i ] = ( char ) (( temp [ i ]+ n )> 'Z' ? ( temp [ i ]+ n - 1 )% 'Z' + 'A' : ( temp [ i ]+ n )); result += temp [ i ]; } return result ; } public static void main ( String [] args ) { Caesar c = new Caesar (); System . out . println ( "s는 'a B z', n은 4인 경우: " + c . caesar ( ...