Emirp
N
直到 EOFEmirp
N is not prime.
N is prime.
N is emirp.
while
迴圈重複輸入整數 N
int N, rev_N;
while(scanf("%d", &N) != EOF){
printf("%d ", N);
...
}
for
迴圈檢查是否有可整除的因數,若有則代表質數,並更改 flag1
的狀態;為何迴圈跑到 sqrt(N)
flag1 = true;
for(i = 2; i <= sqrt((double)N); i++){
if(N % i == 0){
flag1 = false;
break;
}
}
N
為合數就不用再計算;若為質數就用 while
把 N
顛倒,並再判斷一次若顛倒後是同個數,根據題目要求要撇除此情況,所以就更新 flag2
的狀態
if(flag1){
int temp = N;
while(temp > 0){
rev_N = rev_N * 10 + temp % 10;
temp = temp / 10;
}
if(rev_N == N){
flag2 = false;
}
else{
...
}
}
for
迴圈再檢查一次顛倒後的 rev_N
是否為質數
for(i = 2; i <= sqrt((double)rev_N); i++){
if(rev_N % i == 0){
flag2 = false;
break;
}
}
#include<stdbool.h>
#include<stdio.h>
#include<math.h>
int main(){
int N, rev_N;
bool flag1, flag2;
int i;
while(scanf("%d", &N) != EOF){
printf("%d ", N);
flag1 = true;
flag2 = true;
rev_N = 0;
for(i = 2; i <= sqrt((double)N); i++){
if(N % i == 0){
flag1 = false;
break;
}
}
if(flag1){
int temp = N;
while(temp > 0){
rev_N = rev_N * 10 + temp % 10;
temp = temp / 10;
}
if(rev_N == N){
flag2 = false;
}
else{
for(i = 2; i <= sqrt((double)rev_N); i++){
if(rev_N % i == 0){
flag2 = false;
break;
}
}
}
}
if(flag1 && flag2){
printf("is emirp.\n");
}
else if(flag1){
printf("is prime.\n");
}
else{
printf("is not prime.\n");
}
}
return 0;
}