프로그래머스 C#/Lv.1

[프로그래머스 C#] 소수 찾기

썩은피망 2024. 6. 9. 19:59
반응형

문제 살펴보기

  1. 숫자 n보다 작은 소수의 개수를 반환합니다.

제한사항

  • 2 ≤ n ≤ 10,000,000

입출력 예

n result
10 4
5 3

 

using System;

public class Solution {
    public int solution(int n) {
        int answer = 0;
        
        for(int i = 2; i <= n; i++)
        {
            if(Decimal_Test(i))
                answer++;
        }
        
        return answer;
    }
    
    public bool Decimal_Test(int n)
    {
        int temp = (int)Math.Sqrt(n);
        for(int i = 2; i <= temp; i++)
        {
            if(n % i == 0)
                return false; //소수아님!
        }
        return true;//소수임!
    }
}

반응형