In: Computer Science
You have to write a program that will read an array from a file and print if the numbers in the file are right truncatable primes. A right truncatable prime is a prime number, where if you truncate any numbers from the right, the resulting number is still prime. For example, 3797 is a truncatable prime number number because 3797, 379, 37, and 3 are all primes. Input-Output format: Your program will take the file name as input. The first line in the file provides the total number of values in the array. The subsequent lines will contain an integer value.
For example a sample input file “file1.txt” is:
3
397
73
47
Your output will be a yes/no for each value in the input file.
$./first file1.txt
no
yes
no
in C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LSIZ 128
#define RSIZ 10
int checkPrime(int n){
int i;
for(i=2;i<n;i++){
if(n%i == 0)
return 0;
}
return 1;
}
int main(void)
{
char line[RSIZ][LSIZ];
char yes[5] = "yes", no[5] = "no";
FILE *fptr = NULL;
int i = 0, n, flag = 1;
int tot = 0;
fptr = fopen("file1.txt", "r");
while(fgets(line[i], LSIZ, fptr))
{
line[i][strlen(line[i]) - 1] = '\0';
i++;
}
fclose(fptr);
fptr = fopen("file2.txt", "w");
tot = i;
for(i = 0; i < tot; ++i)
{
flag = 1;
n = atoi(line[i]);
printf("%d\n", n);
while(n!=0){
if(!checkPrime(n)){
flag = 0;
break;
}
n = n/10;
}
if(flag == 1){
printf("yes\n");
fputs(yes,
fptr);
}
else{
printf("no\n");
fputs(no,
fptr);
}
}
fclose(fptr);
return 0;
}