Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

A prime number is a positive integer that has factors of 1 and itself. The first

ID: 3819608 • Letter: A

Question

A prime number is a positive integer that has factors of 1 and itself. The first few prime numbers are: 2, 3, 5, 7, 11, 13, 17, 19. You will write a Boolean function that takes a positive integer as input and returns "True" if the input is prime and "False" if the input is not prime. Using this function. Write a program that will find the first 100 prime numbers. Note that this does not say the prime numbers between 1 and 100. There will be suitable messages explaining the output which will be a list of the numbers and the message Prime or not prime. This output will be in the form of a file by name prime.dat. You may wish to do some formatting of the output to make the file more compact.

Explanation / Answer

#include<iostream>
#include<fstream>
using namespace std;

bool isPrime(int n) {
   for (int i = 2; i < n; i++) //if divible by any number between 2 and n-1 (both inclusive)
       if (n%i == 0)
           return false; //the number is not prime
   return true; //else it is divisible
}

int main() {
   int count = 0;
   ofstream output("prime.dat"); //open file
   if (output.is_open()) { //chk if the file is successfully opened
       for (int i = 2; count < 100; i++) //increase i till count reaches 100
           if (isPrime(i)) {
               output<<i<<" is Prime"<<endl; //peint prime numbers to the file
               count ++; //increase prime count
           }
       output.close();
   }
}

hello champ. I hope you will like the code. I tried my best to keep it simple and to make your life easier, I have commented almost all lines of the code. Please let me know if you face any problem with the code.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote