2009年2月27日 星期五

Q10235: Simply Emirp

/*
注意:字串assign完之後要在最後一位後面加上 '\0' 不然會讀錯
Run time: 0.040
*/
#include <stdio.h>
#include <string.h>
#define N 1000000
bool isprime[N+1];

int main()
{
int i, j;

for ( i = 2; i*i <= N; i++)
if (!isprime[i])
for ( j = 2*i; j <= N; j+=i)
isprime[j] = true;

int n;
int reverse;
int len;
char str[7];
char rev[7];

while (scanf("%d", &n) != EOF)
{
if (isprime[n])
{
printf("%d is not prime.\n", n);
continue;
}

snprintf(str, sizeof(str), "%d\0", n);

len = strlen(str);

for ( i = len-1, j = 0; i >= 0; i--)
rev[j++] = str[i];

rev[j] = '\0';

sscanf(rev, "%d", &reverse);

if (!isprime[reverse] && (n != reverse))
printf("%d is emirp.\n", n);
else
printf("%d is prime.\n", n);

}

return 0;
}

沒有留言: