完美的素数
Time Limit: 1000 ms
Memory Limit: 65536 KiB
Problem Description
素数又称质数。指一个大于1的自然数,除了1和此整数自身外,不能被其他自然数整除的数。我们定义:如果一个素数是完美的素数,当且仅当它的每一位数字之和也是一个素数。现在给你一个正整数,你需要写个程序判断一下这个数按照上面的定义是不是一个完美的素数。
Input
输入包含多组测试数据。
每组测试数据只包含一个正整数 n (1 < n <= 10^6)。
Output
对于每组测试数据,如果 n 是完美的素数,输出“YES”,否则输出“NO”(输出均不含引号)。
Sample Input
11 13
Sample Output
YES NO
Hint
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QwQ {
class Program {
public static int[] prime = new int[MAX/3]; //定义全局变量 key[value] -> (第N-1个素数)[第N-1个素数值]
public static bool[] isPrime = new bool[MAX]; //判断是否为素数 数[是/否]
public static int cntOfPrime = 0; //总素数个数
public const int MAX = (int)1e6 + 100; // 最大值
static void Main(string[] args) {
getPrime();
while(true) {
string n = Console.ReadLine();
if(jdg(n)) {
Console.WriteLine("YES");
}
else {
Console.WriteLine("NO");
}
}
Console.ReadKey();
}
public static bool jdg(string n) {
int m = int.Parse(n);
if(m >= 0 && isPrime[m] == true) {
int sum = 0;
foreach(char i in n) {
sum += i - '0';
}
if(isPrime[sum] == true) return true;
}
return false;
}
public static void getPrime() {
for(int i = 2;i < MAX;i ++) {
isPrime[i] = true;
}
for(int i = 2;i < MAX;i ++) {
if(isPrime[i] == true) {
prime[cntOfPrime++] = i;
}
for(int j = 0;j < cntOfPrime && i * prime[j] < MAX;j++) {
isPrime[i * prime[j]] = false;
if(i % prime[j] <= 0) break;
}
}
}
}
}
/***************************************************
Take time: 76ms
Take Memory: 5344KB
****************************************************/