끄적끄적
프로그래머스 lv1 [소수 만들기] 본문
출처 : https://programmers.co.kr/learn/courses/30/lessons/12977
코딩테스트 연습 - 소수 만들기
주어진 숫자 중 3개의 수를 더했을 때 소수가 되는 경우의 개수를 구하려고 합니다. 숫자들이 들어있는 배열 nums가 매개변수로 주어질 때, nums에 있는 숫자들 중 서로 다른 3개를 골라 더했을 때
programmers.co.kr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<bits/stdc++.h> | |
using namespace std; | |
bool IsPrime(int num){ | |
if(num==1) return false; | |
if(num==2) return true; | |
if(num%2 == 0) return false; | |
for(int i=3; i<=sqrt(num); i++){ | |
if(num%i == 0) return false; | |
} | |
return true; | |
} | |
int solution(vector<int> nums) { | |
int answer = 0; | |
for(int i=0; i<nums.size()-2; i++){ | |
for(int j=i+1; j<nums.size()-1; j++){ | |
for(int k=j+1; k<nums.size(); k++){ | |
int sum = nums[i]+nums[j]+nums[k]; | |
if(IsPrime(sum)) answer++; | |
} | |
} | |
} | |
return answer; | |
} |
주어진 배열에서 3개의 숫자를 고르면 되므로 3중 for문 이용
IsPrime이라는 소수 판별 함수를 사용하여 소수 판별
1일 경우는 무조건 소수가 아니니 예외 처리
2는 짝수 중 유일한 소수니 예외 처리
2로 나눠지면 소수가 아니니 예외처리
3으로 나눌 때부터 for문 사용해서 num의 제곱근까지 돌린다(제곱근까지 돌리면 충분하다고 한다)
-> 에스트라토네스의 체
이 때 어느 한 수로라도 나누어 떨어지면 소수가 아니므로 false 리턴
소수인 경우 answer++을 해준다
'코테준비' 카테고리의 다른 글
프로그래머스 lv2 [카펫] (0) | 2021.10.30 |
---|---|
프로그래머스 lv2 [주식가격] (0) | 2021.10.30 |
프로그래머스 lv1 [숫자 문자열과 영단어] (0) | 2021.10.27 |
프로그래머스 lv2 [멀쩡한 사각형] (0) | 2021.10.27 |
프로그래머스 [로또의 최고 순위와 최저 순위] (0) | 2021.10.14 |