Write a program that » Firstly, asks the user for value of positive int variable
ID: 3681341 • Letter: W
Question
Write a program that » Firstly, asks the user for value of positive int variable N (ensure N>100) » Secondly, the program generates 25 random numbers in the interval [1, N]and writes them one below the other in a file named Random.txt » Next, the program should read the numbers one by one till end of the file is reached (using loop) and check if the number read is a prime or not. A prime number is a number that is divisible only by itself and 1. (e.g. 5 is Prime because it is only divisible by 1 and 5. However, 6 is not prime, rather it is composite because it can be divided by 1, 2, 3, and 6.) A number num is prime if it is not divisible by any number from 2 to Vnum. 1 is not a prime in this problem » Finally, display on the terminal screen, list of all prime numbers found in the file.Explanation / Answer
#include<iostream>
#include<stdlib.h>
#include<fstream>
using namespace std;
bool isPrime(int n);
int main(){
int N = 0;
// declaring output tstream
ofstream out("Random.txt");
int random;
// reading a number till user input a number >100
while(N <= 100){
cout<<"Enter a number(N>100): ";
cin>>N;
}
// generating 25 random numbers in range [1-N] and writting to file
for(int i=1; i<=25; i++){
random = rand()%N + 1; // in range [1-N]
out<<random<<endl;
}
// reading file
// input stream
ifstream in("Random.txt");
while(in>>random){
if(isPrime(random))
cout<<random<<endl;
}
return 0;
}
bool isPrime(int n){
// iterating through 2 to (n/2).
// why n/2 ? because n/2 (half of any number) is the maximum number that divides n completely.
// so, checking with numbers after n/2 is useless.
// a number is prime if it is divisible by only 1 and itself. So check from 2 to n/2, if it is divisible by any
// number in this range , then this is not prime
for(int i=2; i<=n/2; i++){
if(n%i == 0)
return false;
}
return true;
}
/*
Output:
Enter a number(N>100): 115
47
53
1
107
2
79
17
3
Random.txt:
104
47
53
26
99
1
107
48
35
2
18
63
76
110
79
87
16
57
78
82
17
104
3
50
48
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.