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
#include <iostream> #include <fstream> #include <cstring> using namespace std; bool isPrime(int value) { for(int i=2; i<=value/2; i++) { if(value%i == 0) { return false; } } return true; } bool isRightTruncatablePrime(int x) { while(x != 0) { if(!isPrime(x)) { return false; } x = x / 10; } return true; } int main(int argc, char *argv[]) { if(argc != 2) { cout << "Missing argument" << endl; return 0; } char *fileName = argv[1]; ifstream f(fileName); int size; f >> size; while(size-- > 0) { int x; f >> x; if(isRightTruncatablePrime(x)) { cout << "yes" << endl; } else { cout << "no" << endl; } } return 0; }
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.