본문 바로가기

컴퓨터 프로그래밍/알고리즘

프로그래머스_소수찾기

1부터 입력받은 숫자 n 사이에 있는 소수의 개수를 반환하는 함수, solution을 만들어 보세요.

소수는 1과 자기 자신으로만 나누어지는 수를 의미합니다.
(1은 소수가 아닙니다.)

제한 조건

  • n은 2이상 1000000이하의 자연수입니다.

입출력 예

n                        result

10 4
5 3

입출력 예 설명

입출력 예 #1
1부터 10 사이의 소수는 [2,3,5,7] 4개가 존재하므로 4를 반환

입출력 예 #2
1부터 5 사이의 소수는 [2,3,5] 3개가 존재하므로 3를 반환

 

1. ArrayList를 2~n까지의 정수를 값으로 가지게 만듭니다. 

2. 2를 제외한 2의배수를 지웁니다. 그 다음 요소를 제외한 그 요소의 배수를 지웁니다.(for)

4. n/2까지 합니다. (while)

5. 남아 있는 사이즈를 리턴합니다.

ArrayList에 값을 지우는 방법은 

remove(index)

remove(Obj)

이렇게 두가지인데, integer일 경우에는 index일지 요소값일지 구분해 줘야합니다.

구분하는 방법은 아래와같이 해줍니다. 

list.remove(Integer.valueOf(300));

list.remove(list.indexOf(300));

위와같은 로직으로 했는데, 시간이 많이 걸려서... 통과를 못했습니다. 

public class l_25 {
public static int solution(int n) {
		int answer = 0;

		if (n == 2 || n == 3) {
			return 1;
		}
		ArrayList<Integer> list = new ArrayList<>();
		for (int i = 2; i <= n; i++) {
			list.add(i);
		}
		
		int j = 0;
		while(list.get(j)<=n/2) {			
			for (int i = 2; i <= n / list.get(j); i++) {
				list.remove(Integer.valueOf(i * list.get(j)));
			}
			j++;
		}
		return list.size();
	}
	public static void main(String[] args) {
		System.out.println(solution(10));
		System.out.println(solution(5));
	}
}

다시해봐야겠습니다....

 

그래서 다시 해봤습니다. 

이번엔 재귀적인 방법으로 풀어봤습니다.

그런데, 아래의 방법도 효율성에서... 실해가 떴습니다....ㅋㅋㅋㅋ

public static int solution(int n) {
		int result = 0;
		if(n==2) {
			return 1;
		}
		if(n==3) {
			return 2;
		}
		
		int i = 2;
		boolean isSosu = true;
		while (i * i <= n) {
			if (n % i == 0) {
				isSosu = false;
				break;
			}
			i++;
		}
		if(isSosu) {
			result = solution(n-1)+1;
		}else {
			result = solution(n-1);
		}
		return result;
	}

직접 다 때려넣었습니다.

public static int solution(int n) {
		int result = 2;
		if(n==2) {
			return 1;
		}
		if(n==3) {
			return 2;
		}
		for (int j = 4; j <= n;j++ ) {
			int i = 2;
			boolean isSosu = true;
			while (i * i <= j) {
				if (j % i == 0) {
					isSosu = false;
					break;
				}
				i++;
			}
			if(isSosu) {
				result++;
			}	
		}
		
		return result;
	}

	public static void main(String[] args) {
		System.out.println(solution(10));
		System.out.println(solution(5));
	}

성공입니다. 

 

<남풀이>

- 비슷한것 같습니다.

  int numberOfPrime(int n) {
        int result = 0;

        for(int i = 2; i <= n; i++){
            boolean flag = false;
            for(int j = 2; j < i; j++){
                if(i % j == 0 ){          //약수가 하나라도 있으면 플래그 세움
                    flag = true;
                }               
            }
            if(flag == false )
                result++;
        }
        return result;             //2부터 n까지의 소수의 갯수(1은 소수가 아님)
    }

알아야할 내용.

약수갯수 세는 것과 소수 판별하는 내용 숙지하면 좋을 것 같네요.

https://curt-park.github.io/2018-09-17/algorithm-primality-test/