알고리즘 풀이/프로그래머스

[프로그래머스][JAVA] 카펫 (완전탐색)

배게 2022. 3. 31. 07:16
728x90

근의 공식 ↓

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
    public int[] solution(int brown, int yellow) {
        
        // ax^2 + bx + c = 0의 근의 공식
        // int a = 1;
        int b = -(brown+4)/2;
        int c = brown + yellow;
        
        int hw1 = (-+(int)(Math.sqrt(b*b-4*c)) )/2;
        int hw2 = (--(int)(Math.sqrt(b*b-4*c)) )/2;
        // System.out.println(h1);
        // System.out.println(h2);
        int h = Math.min(hw1,hw2);
        int w = Math.max(hw1,hw2);
        
        return new int[]{w,h};
    }
}
cs

 

 

 

 

완전탐색 ↓

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.*;
 
class Solution {
    public int[] solution(int brown, int yellow) {
        int total = brown+yellow;
        
        for(int i=3; i<=total; i++){
            if(total%i==0){
                int a = i;
                int b = total/i;
                if((a-2)*(b-2)==yellow){
                    return new int[]{Math.max(a,b), Math.min(a,b)};
                }
            }         
        }
        throw new IllegalArgumentException();
    }
}
cs