#include <iostream>
using namespace std;
int main()
{
char ch;
int n;
do {
cout << "Enter a number:";
cin >> n;
if (n % 2 == 0)
cout << "The number is even.\n";
else
cout << "The number is odd.\n";
bool prime;
for (int i = 2; i < n; ++i) {
if (n % i == 0)
prime = true;
}
if (prime) {
cout << "The number is not prime.";
}
else
cout << "The number is prime.";
cout << "Do you want to continue?[y/n]";
cin >> ch;
} while (ch == 'y' || ch == 'Y');
}
If the loop enters once into if(prime) then it never goes in the else.
On first run of loop if 3 is entered, it outputs prime. Then in next if 4 if entered it show not prime but after that whenever any prime number is entered it shows not prime.
first of all your
bool prime;
is not initialized. Second it should be initialized inside do while() loop and it is better to move that variable declaration there:
bool prime = false; // move it here and initialize
for (i = 2; i < n; ++i) {
if (n % i == 0)
prime = true;
}
and you use boolean flag in reverse, which makes your program unreadable, you better fix that:
bool prime = true; // move it here and initialize
for (i = 2; i < n and prime; ++i) {
if (n % i == 0)
prime = false;
}
if (prime)
cout << "The number is prime.";
else
cout << "The number is not prime.";
Related
I am writing a program that takes multiple user inputs, and counts how many prime numbers there are, and which number is the greatest and smallest of the inputs. However, I am stuck. when I run the code, it thinks every new input is the greatest number. for example, if I enter 1, 2, 3, 2... It says the greatest number is 2. It takes the last integer inputted and thinks that is the greatest number. I have no started on the lease common number yet, but if I am able to understand how to get the greatest number, I bet I can get the least. Thanks guys!
#include <iostream>
using namespace std;
int main() {
int startstop = 1;
cout << "start program?" << endl;
int begin = 0;
int primecounter = 0;
cin >> begin;
if (begin >= 0) {
while (startstop != 0) {
cout << "enter any number, or press Q to process." << endl;
int oldnum = 0;
int userinput=0;
int newnum = userinput;
int greatestnum = 0;
int greatestcounter = 0;
cin >> userinput;
int x;
bool is_prime = true;
if (userinput == 0 || userinput == 1) {
is_prime = false;
}
// loop to check if n is prime
for (x = 2; x <= userinput / 2; ++x) {
if (userinput % x == 0) {
is_prime = false;
break;
}
}
if (is_prime) {
primecounter++;
}
//check if input is greater than previous input
if (greatestnum > userinput) {
greatestnum = userinput;
}
cout << "prime count: " << primecounter << endl;
cout << "greatest num: " << greatestnum << endl;
userinput = 0;
}
return 0;
}
}
greatestnum is only assined if it's greater than the user input. Since it's initialized to 0, the if statement,
if (greatestnum > userinput) {
greatestnum = userinput;
}
will be false unless the user input is less than zero. If you want to make it the greatest from all user inputs, flip it to < and move the int greatestnum = 0; to right above the if (begin >= 0) {.
if (greatestnum < userinput) {
greatestnum = userinput;
}
#include <iostream>
using namespace std;
int main() {
int startstop = 1;
cout << "start program?" << endl;
int begin = 0;
int primecounter = 0,greatestnum = 0,oldnum = 0,userinput = 0;
cin >> begin;
if (begin >= 0) {
while (startstop != 0) {
cout << "enter any number, or press Q to process." << endl;
cin >> userinput;
int x;
bool is_prime = true;
if (userinput == 0 || userinput == 1) {
is_prime = false;
}
// loop to check if n is prime
for (x = 2; x <= userinput / 2; ++x) {
if (userinput % x == 0) {
is_prime = false;
break;
}
}
if (is_prime) {
primecounter++;
}
//check if input is greater than previous input
if (userinput > oldnum) {
greatestnum = userinput;
oldnum = userinput;
}
cout << "prime count: " << primecounter << endl;
cout << "greatest num: " << greatestnum << endl;
userinput = 0;
}
return 0;
}
}
Initialize 'oldnum=0' , 'userinput=0' and 'greatestnum=0' outside the loop. And there were some error in logic. If userinput is greater the old num the update greatest num=userinput and oldnum=userinput.
While getting user input, I set the smallest and largest numbers input into their own variables, but for whatever reason they start out = to 0.
Code:
#include <iostream>
using namespace std;
int main()
{
int num;
string var;
int sum = 0;
int i;
int largest = INT_MIN;
int smallest = INT_MAX;
int j = 0;
int prime = 0;
do {
cout << "Please enter a series of numbers, press (Q or q) to process: ";
cin >> num;
if (cin.fail())
{
cin.clear();
cin >> var;
if (var != "Q" && var != "q")
{
cout << "Invalid input, try again" << endl;
}
}
if (num > largest)
{
largest = num;
}
if (num < smallest)
{
smallest = num;
}
if (num == 0 || num == 1)
{
prime = prime;
}
else
{
for (i = 2; i <= num / 2; i++)
{
if (num % i == 0)
{
j = 1;
break;
}
}
if (j == 0)
{
prime++;
}
}
sum += num;
cout << "The corresponding element for the cumulative total sequence is: " << sum << endl;
cin.ignore(sum, '\n');
} while (var != "Q" && var != "q");
cout << endl;
cout << "Largest number: " << largest << endl;
cout << "Smallest number: " << smallest << endl;
cout << "How many prime numbers? " << prime << endl;
cout << "Have a great day!" << endl;
}
Here is an example of the program being run.
Program example
The smallest number here should be 8, and the issue is that it begins at 0. The same thing with the largest number.
Program example #2
Your loop is testing the "num" variable even if the user inputs q or Q, adding an else statement else break; after the if (var != "Q" && var != "q") will fix it.
For the future, always keep in mind that when the "if" function fails, it will move on to the next line, if you need to to not execute, you either need to break out of the loop or change the structure of your code.
I have written the bulk majority of the program, I'm just having trouble debugging it. Something must be wrong with my computation of the prime numbers. For anything I try, it says there are 0 prime numbers. Any help would be greatly appreciated. Code and output are below.
Note: For this program, I am not allowed to use vectors or arrays.
#include <iostream>
#include <cmath>
using namespace std;
// FUNCTION PROTOTYPE FOR read_range
void read_range(int &lower, int &upper);
// FUNCTION PROTOTYPE FOR is_prime
bool is_prime(const int num);
// FUNCTION PROTOTYPE FOR display_primes
void display_primes(const string &prime, const int lower, const int upper);
// DO NOT MODIFY THE MAIN ROUTINE IN ANY WAY
int main()
{
int imin(0), imax(0);
// Read in range
read_range(imin, imax);
// Print prime numbers
cout << endl;
display_primes("Primes: ", imin, imax);
return 0;
}
// DEFINE FUNCTION read_range() HERE:
void read_range(int &lower, int &upper){
cout << "Enter minimum and maximum: ";
cin >> lower >> upper;
while (lower < 2 || upper < 2 || lower > upper){
if (lower < 2 || upper < 2) {
cout << "Error. Minimum and maximum must be at least 2." << endl; }
else if (lower > upper) {
cout << "Error. Minimum must be less than maximum." << endl; }
cout << "Enter minimum and maximum: ";
cin >> lower >> upper; }}
// DEFINE FUNCTION is_prime() HERE:
bool is_prime(const int num) {
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return 0; } // Is not prime
else {
return 1; }}} // Is prime
// DEFINE FUNCTION display_primes() HERE:
void display_primes(const string &prime, const int lower, const int upper) {
int count = 0;
int commaCheck = 0;
for (int i = lower; i <= upper; i++) {
if (is_prime(i)) {
count = count + 1; }}
if (count == 1) {
cout << "There is " << count << " prime number in this range." << endl; }
else {
cout << "There are " << count << " prime numbers in this range." << endl; }
if (count != 0) {
cout << prime;
for (int i = lower; i <= upper; i++) {
if (is_prime(i)) {
if (count == 1) {
cout << i;}
else {
commaCheck = commaCheck + 1; }
if (commaCheck != count) {
cout << i << ","; }
else {
cout << i; }}}
cout << endl; }
else {
cout << "No primes to display." << endl; }}
Output (with input of 2,3)
Enter minimum and maximum:
There are 0 prime numbers in this range.
No primes to display.
is_prime has two issues.
If sqrt(num) is less than 2 the loop never executes and your function has undefined behaviour as it ends without returning (your compiler probably should have warned you about this issue)
If the number is not even then in the first iteration of the loop you call return 1 which means all odd numbers will be labelled as prime.
Changing your loop to this will work (if not be very efficient, there are much better algorithms for finding prime numbers):
bool is_prime(const int num) {
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
This is one of the default algorithms for checking how many numbers between two intervals are prime numbers, there are many alternatives, but this is what i prefer and is short and easy to remember
#include <iostream>
using namespace std;
int main(){
int i1min, i1max;
int i, j, k = 0;
bool primeTest;
cin >> i1min;
cin >> i1max;
for(i=i1min; i<=i1max; i++) {
primeTest = false;
for (j=2; j<=i/2; j++) {
if (i % j == 0) {
primeTest = true;
break;
}
}
if (primeTest == false)
k++;
}
cout << k;
return 0;
}
I've been learning C++ for few weeks, however, I got stuck, I have a function isPrime(), works great to show if the number is prime or no, I need to display all the Prime numbers which are less than 200. But it's not working see line marked with comment
#include <iostream>
using namespace std;
// Function Prototypes
bool isPrime(int);
int main()
{
int Num;
cout << "This program let you know if the number entered is a "
<< "prime number.\nEnter a number: ";
cin >> Num;
cout << "The number " << Num;
if (isPrime(Num))
{
cout << " is a Prime number." << endl;
}
else
cout << " is not a Prime number." << endl;
return 0;
}
//isPrime
bool isPrime(int Num)
{
if (Num > 1)
{
for (int i = 2; i <= Num; ++i)
{
if (Num % i == 0)
{
if(Num == i)
return true;
else if
for(int n = 2; n < 200; n++) { // HERE
// isPrime will be true for prime numbers
isPrime = isPrimeNumber(n);
if(isPrime == true)
cout<<n<<" ";
}
return 0;
else
return false;
}
}
}
return false;
}
You added the loop in the wrong place. That function is only for checking a particular number. Either you would need to make another function to print all the prime numbers which are less than 200 or you can directly add the loop in the main() function, like i did.
#include <iostream>
using namespace std;
// Function Prototypes
bool isPrime(int);
int main()
{
int Num;
cout << "This program let you know if the number entered is a "
<< "prime number.\nEnter a number: ";
cin >> Num;
cout << "The number " << Num;
// Check numbers here
for(int n = 2; n < 200; n++) {
if (isPrime(n)){
cout << n << " is a Prime number." << endl;
}
}
return 0;
}
//isPrime - This is your original isPrime Code
bool isPrime(int Num)
{
if (Num > 1)
{
for (int i = 2; i <= Num; ++i)
{
if (Num % i == 0)
{
if(Num == i)
return true;
else
return false;
}
}
}
return false;
}
I am suppose to make a program that asks a user to input an integer 'n' between 1 and 100, and have an input validation loop. The program will then calculate the first 'n' prime numbers and print them. So I figured out how to calculate the prime numbers and display them, 10 numbers per line, all in the main function. What I have to do is to have a function called isPrime() that takes an integer and returns true if it is prime and false otherwise. I'm not sure how to go about this. This is the code I have for function main().
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int number;
int count = 0;
cout << "Enter an integer between 1 and 100: ";
cin >> number;
while (number < 0 || number > 100)
{
cout << "Invalid number." << endl;
cout << "Enter an integer between 1 and 100: ";
cin >> number;
}
cout << "The first " << number << " primes: \n" << endl;
for (int i = 2; number > 0; ++i)
{
bool isPrime = true;
for (int j = 2; j < i; ++j)
{
if (i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
count++;
--number;
cout << setw(5) << i;
if (count % 10 == 0)
cout << endl;
}
}
cout << endl;
system("pause");
return 0;
}
Any help is good, thanks in advance.
You seem to be testing i % j for every j lower then i. But if you tested for j = 3 then you can exclude all multiples of 3. When a number can't be divided by 3 it can't be divided by 6. This will improve performance.
You can also implement the AKS primalty test https://en.wikipedia.org/wiki/AKS_primality_test
This might be a little more work. I don't know the details of this test but it is deterministic and works on all numbers.
If you want a function bool isPrime(int number) you can just extract this code from your main method, it looks something like this:
bool isPrime(int number){
for (int j = 2; j < number/2; ++j)
{
if (number % j == 0)
{
return false;
}
}
return true;
}
The for loop in the main function will be something like:
for (int i = 2; number > 0; ++i)
{
if (isPrime(i))
{
count++;
--number;
cout << setw(5) << i;
if (count % 10 == 0)
cout << endl;
}
}