The Test Write a program, TestForPrimes, that reads a file of whole numbers and
ID: 3620575 • Letter: T
Question
The TestWrite a program, TestForPrimes, that reads a file of whole numbers and writes only the prime numbers to a second file. Write you name as comment at the beginning of the program
A prime number is a positive integer that has two distinct divisors – 1 and itself. By this definition 1 is not a prime number.
How do recognize prime numbers?
Write a function isPrime that returns true if its parameter is a prime number and false if it is not a prime number.
An algorithm for the function is
number = abs(number)
if number = 0 then return false
else if number = 1 then return false
else if number modulo 2 is 0 then return false
else
factor = 3
remainder = number modulo factor
upper bound = floor(square_root(number))
while factor <= upper bound and remainder ? 0
factor = factor + 2
remainder = number modulo factor
end while
if factor > upper bound then
return true
else
return false
end if
end if
Note “modulo” is the C++ modulus operator “%”
There is a C++ floor function, a C++ sqrt function, and a C++ abs function
You have to include cmath to use these functions
Explanation / Answer
please rate - thanks //Name#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
bool isPrime(int);
int main()
{
char filename[80];
int num;
ifstream in;
ofstream out;
cout<<"Enter name of input file: ";
cin>>filename;
in.open(filename);
if(in.fail())
{ cout<<"input file did not open please check it ";
system("pause");
return 1;
}
cout<<"Enter name of output file: ";
cin>>filename;
out.open(filename);
in>>num;
while(in)
{if(isPrime(num))
out<<num<<endl;
in>>num;
}
out.close();
in.close();
return 0;
}
bool isPrime(int n)
{int i;
if(n<0)
n=-n;
if(n<=1)
return false;
for(i=2;i<=floor(sqrt(n));i++)
if(n%i==0) //if you find a factor the number isn't prime
return false;
return true; // get here only if no factors
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.