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

I am trying to write a “C++” program to allow the user to input a range of integ

ID: 3675199 • Letter: I

Question

I am trying to write a “C++” program to allow the user to input a range of integers and would output all the integers between those values. I already came up with a program, but it outputs 2 as a non-prime number when in fact it's prime. Can anyone help me, I am at a total loss here. I will post the code below:   

#include<iostream>

#include<cmath>

using namespace std;

int main(){

int start, end;

cout << "Please enter the start and end of a range of integers." << endl;

cout << "I will tell you what integers in the range are non-prime numbers" << endl;

cout << endl;

cout << "starting number" << endl;

cin >> start;

cout << "ending number" << endl;

cin >> end;

double s;

for (int x = start; x <= end; x++){

s = sqrt(x) + 1;

for (int y = 2; y <= s; y++){

if (x % y == 0){

cout << x << " is a non-prime number" << endl;

}

}

}

system("pause");

}

Explanation / Answer

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

int main(){
int start, end;
cout << "Please enter the start and end of a range of integers." << endl;
cout << "I will tell you what integers in the range are non-prime numbers" << endl;
cout << endl;
cout << "starting number" << endl;
cin >> start;
cout << "ending number" << endl;
cin >> end;
double s;

for (int x = start; x <= end; x++){
s = sqrt(x) + 1;

for (int y = 2; y <= s; ++y){
if (x==2)
continue;
if (x % y == 0){
cout << x << " is a non-prime number" << endl;
}
}
}

system("pause");
}

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