C# 백준 1978번 소수찾기
2022. 1. 3. 16:53ㆍC#/[백준] 기본 수학2
코드 :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _1
{
internal class Program
{
static void Main(string[] args)
{
//1 3 5 7 전체길이 = 4, number = 1, 출력 = 3
int N = Convert.ToInt32(Console.ReadLine());
string input = Console.ReadLine();
string[] inputdata = input.Split(' ');
int number = 0; //소수가 아닌값들을 찾아서 전체 길이에서 빼기
for (int i = 0; i < inputdata.Length; i++)
{
if (Convert.ToInt32(inputdata[i]) == 1) //1은 예외처리
{
number++;
}
else
{
//제곱근 이하의 수에서 나누어 떨어지지 않으면 소수이므로 제곱근의 버림값을 저장
double sqrt = Math.Truncate(Math.Sqrt(Convert.ToInt32(inputdata[i])));
for (double j = 2; j <= sqrt; j++)
{
if (Convert.ToInt32(inputdata[i]) % j == 0)
{
number++;
break;
}
}
}
}
Console.WriteLine((inputdata.Length - number));
}
}
}
기본수학2에는 소수문제가 많다. 소수문제를 쉽게 풀기 위해 소수를 구하는 방법을 검색해보니 제곱근 이하의 수에서 나누어 떨어지지 않으면 소수라는 점을 알게 되어 그 점을 활용하여 풀었다.
'C# > [백준] 기본 수학2' 카테고리의 다른 글
C# 백준 9020번 골드바흐의 추측 (0) | 2022.01.03 |
---|---|
C# 백준 4948번 베트르탕 공준 (0) | 2022.01.03 |
C# 백준 1929번 소수 구하기 stringBuilder활용 (0) | 2022.01.03 |
C# 백준 11653번 소인수분해 (0) | 2022.01.03 |
C# 백준 2581번 소수 (0) | 2022.01.03 |