C++ : using prime number and not a prime number - c++

I need to write a program in C++ that receives a positive number greater than 2 from the user, and prints whether the number is prime or not.
Reminder: A number is prime if it is divisible by a remainder only in itself and in 1, and not in any other number. Therefore, primary 2 is divisible only by itself and 1, but non-primary 4 is also divisible by 2.
but the probleme is in the loop, He repeats the steps
and I have a problem with the number 2177 which is not a prime number.
#include <iostream>
#include <math.h>
using namespace std;
void main()
{
int nNumber;
int i;
cout << "Enter a number:" << endl;
cin >> nNumber;
if (nNumber >= 2)
{
for (i = 2; i <= sqrt (nNumber); i++)
{
if (nNumber % i == 0)
{
// he is repete the step her
cout << nNumber << " is not a prime number." << endl;
}
}
if (nNumber % i != 0)
{
cout << nNumber << " is a prime number. " << endl;
}
}
system("pause");
}

You do not describe what problem you have, but what I get when I run this program is:
2177 is not a prime number.
2177 is a prime number.
sh: 1: pause: not found
First your applications finds correctly that 2177 is not prime (at i=3), but then you continue your loop (which is not necessary or useful because it will just print the line again if it finds extra values).
However your main problem is that you always execute the line if (nNumber % i != 0), even if a value has been found. At this point i has the fixed value ((int)sqrt(2177)) + 1 (which is 47) because the loop is completed at that point and will stay at that value. Because 2177 is not divisible by 47 you print out the message 2177 is a prime number..

This code should work. Added break statement -
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int nNumber;
int i;
cout << "Enter a number:" << endl;
cin >> nNumber;
if (nNumber >= 2)
{
for (i = 2; i <= sqrt (nNumber); i++)
{
if (nNumber % i == 0)
{
cout << nNumber << " is not a prime number." << endl;
break;
}
}
if (nNumber % i != 0)
{
cout << nNumber << " is a prime number. " << endl;
}
}
system("pause");
return 0;
}

Just define a Boolean variable and set its value to 'true'. You only need to run a loop "n/2 times" as the maximum divisor is half of the actual number. So, if the input number is divisible by any value between '2-n/2', set the value of Boolean variable false. In the end, print the result on the basis of Boolean variable value.
Have a look at this link!
https://www.programiz.com/cpp-programming/examples/prime-number

Related

C++ program to calculate the factorial of even numbers between 5 and 15

When I run the program for an even number less than 5, It prints out the error message but it also gives me the factorial. I don't want the factorial. Here's the code, how do I correct it?
#include <iostream>
using namespace std;
int main()
{
int number, factorial = 1;
cout << "Enter an even number between 5 & 15 to find it's factorial: ";
cin >> number;
if(number % 2 == 0) {
while(number < 5) {
cout << "Error! Enter an even number greater than five: ";
break;
}
while(number > 15) {
cout << "Error! Enter an even number less than fifteen: ";
break;
}
for(int a = 1; a <= number; a++) {
factorial = factorial * a;
}
cout << "factorial of " << number << " is " << factorial;
}
else {
cout << "Error!Enter an even number between 5 & 15 to find it's "
"factorial: ";
}
return 0;
}
This answer shows some corrections to be in your code and provide a working piece of code.
Corrections:
Not a very good idea to write everything in the main function. Try to follow SOLID principles where S stands for single responsibility. Which tells that functions must be small and do exactly one thing. And in your code, you have defined a very big function which does a lot of things.
Avoid nested loops. In your example, you have an if , inside which you have while, while and inside while you have for. This looks messy and is not readable.
Try to be clear in your expression of code, such that when a person reads they understand the flow of data.
Break is something that comes out of a while loop, but it does not mean it will exit the function. So in your example,
while(number<5){
std::cout<<"Error! Enter an even number greater than five: ";
break;
}
After it comes out of this loop, it will go to the next line which is another while loop and then goes on to calculate the function.
Try to use uniform initialization. Instead of int i = 0 use int i{0}. You can read more about uniform initialization on google.
Try not to use "using namespace std or anything else". Very bad practice.
Working piece of code:
bool check_value(int number){
int range = (number < 5 || number > 15) ? false : true;
int even = (number % 2 == 0) ? true : false;
if(range & even){
return true;
}
else{
std::cout << "Error! Please input even number between 5 & 15\n";
return false;
}}
int main(){
int number,factorial=1;
std::cout<<"Enter an even number between 5 & 15 to find it's factorial: \n";
std::cin >> number;
if(check_value(number)){
for (size_t a{1}; a <= number; a++){
factorial = factorial*a;
}
std::cout<<"factorial of " << number <<" is " << factorial << "\n";
}
return 0;
}
As Karl pointed out in the comments, the break statement will break out of exactly one loop, in this case a while loop, and the code outside of the loop will continue to execute.
Also, as Damien pointed out, you need to use a long long int to compute the factorial since the result can exceed the max size of the int datatype.
You could also reformulate your code to make it more readable, something like this:
#include <iostream>
/* Checks if number is valid and can throw error msg */
bool isValidNumber(int num) {
if(num % 2 != 0 || num < 5 || num > 15) {
std::cout << "Error! The number entered is not valid." << std::endl;
return false;
}
return true;
}
/* Calculates factorial and prints its value */
void calculateFactorial(int num) {
long long int factorial = 1;
for(int a = 1; a <= num; a++) {
factorial = factorial * a;
}
std::cout << "factorial of " << num << " is " << factorial << std::endl;
}
int main()
{
int number;
bool isValid;
do {
std::cout << "Enter an even number between 5 & 15 to find it's factorial: ";
std::cin >> number;
isValid = isValidNumber(number);
if(isValid) {
calculateFactorial(number);
}
} while(!isValid);
return 0;
}
Note: Using using namespace std; is considered bad practice because of the possibility of method collisions between a method or methods in the std namespace and methods of some other nanmespace you might create down the road.

"Prime or not" program

I am stuck on this really simple program in C++, where I let the user know the number she/he have entered is prime or not, but, because of some reason, everything works fine during the first loop but things go fishy during the second. I would be more than happy if anyone could help ?
#include <iostream>
using namespace std;
int main(int argc, const char* argv[])
{
int number1 = 5;
int number;
int a = 0;
while (number1 == 5)
{
int b = 1;
cout << "Enter your number and we'll tell you if it's prime or not: ";
cin >> number;
while (a <= number)
{
a++;
if (number % a == 0)
b++;
}
if (b == 3)
cout << "Your number is prime" << endl;
else
cout << "Your number is not prime" << endl;
}
}
The are several problems with your program.
The first one is that the loop starting with statement
while (number1 == 5)
is infinite because number1 is not changed within the loop.
The second one is that you must always initialize variable a to zero within the loop. And it should be defined also within the loop because it is not used outside the loop. The same is valid for variable number.
Take into account that a number is prime if it is divisble by 1 and itself (except number 1). So I would initially set variable b to zero and compare it with 2. It is more clear than to compare it with 3.
The program can look the following way
#include <iostream>
int main()
{
while ( true )
{
std::cout << "Enter your number and we'll tell you if it's prime or not (0-exit): ";
unsigned int number = 0;
std::cin >> number;
if ( number == 0 ) break;
unsigned int n = 0;
unsigned int divisor = 0;
while ( divisor++ < number )
{
if ( number % divisor == 0 ) n++;
}
if ( n == 2 )
std::cout << "Your number is prime" << std::endl;
else
std::cout << "Your number is not prime" << std::endl;
}
}
You missed to reinit a to 0 before the inner while.
This makes it work. However, I suggest you take time to learn to code. It does not look educated.
Also your program won't exit. Not sure what your intention is, but you could omit the number1 variable and simply use while(1) (considering your code stands as is; probably you are at the beginning of your development though, so it depends).
#include <iostream>
using namespace std;
int main(int argc, const char* argv[])
{
int number1 = 5;
int number;
int a = 0;
while (number1 == 5)
{
int b = 1;
cout << "Enter your number and we'll tell you if it's prime or not: ";
cin >> number;
a = 0; <-- Reset to 0 would make it work
while (a <= number)
{
a++;
if (number % a == 0)
b++;
}
if (b == 3)
cout << "Your number is prime" << endl;
else
cout << "Your number is not prime" << endl;
}
}
P.S.: You are new to StackOverflow. So you likely take the answer and get away. Please consider accepting the answer. It's a respectful practice when it solved your issue.

Prime number finding program using bool values

I am trying to write a program in C++ that, given a data file that includes random integers, identifies each integer as prime or not prime, and counts the integers. Here is what I have so far:
#include <iostream>
using namespace std;
int main()
{
int number; //number to be tested
int count = 0; //count of integers in file
cin >> number;
while (cin)
{
bool prime = true;
if (number <= 0)
{
prime = false;
}
else
{
for (int i=2; i<number; i++)
if (number % i == 0)
{
prime = false;
break;
}
}
if (prime = true)
cout << number << " is a prime number." << endl;
if (prime = false)
cout << number << " is not a prime number." << endl;
cin >> number;
count++;
}
cout << "The file contains " << count << " integers" << endl;
return 0;
}
The program compiles, but finds all values in a data set as not prime. Here is what I got as output from a data file:
24 is a prime number.
13 is a prime number.
18 is a prime number.
-25 is a prime number.
42 is a prime number.
0 is a prime number.
2 is a prime number.
The file contains 7 integers
Any suggestions? Am I using the bool values correctly?
Thank you
You are using the assignment operator = instead of the equality comparison operator == when checking if prime is true or false. (You should also use braces for your for loop.)
Heads up that you can check the factors until prime/2 (or sqrt(prime), see below) since nothing greater than half of a number can be a factor of it!
This line:
if (prime = true)
cout << number << " is a prime number." << endl;
is assigning "true" to variable "prime". As a expression, an assignment operation returns the value being assigned, so the expression inside the if evaluates as true and hence, prints that the number is prime.
You have to change = by == . An old trick to avoid these mistakes is to change the sentence as this:
if (true = prime)
cout << number << " is a prime number." << endl;
Then the compiler had warned you about the obvious error.

Summming odd and even numbers in an undetermined range

My assignment is to create a program in which the user inputs a starting value and ending value. The program should then sum all the numbers within that range. In addition it should sum the odd numbers and the even numbers. My issue is determining which numbers in the users range is odd and which is even and then summing these values. The total sum loop works but I have tried multiple other loops for the odd and even sums and have had no success. So if someone could help me sum these numbers based on whether there even or odd.
#include <iostream>
using namespace std;
int main()
{
int sum = 0, start, endnumber;
int sumall = 0, c=0;
cout << "Please enter the starting integer\n";
cin >> start;
cout << "Please enter the ending integer\n";
cin >> endnumber;
while (endnumber <= start)
{
cout << "Please enter the starting integer\n";
cin >> start;
cout << "Please enter the ending integer\n";
cin >> endnumber;
}
while (start <= endnumber)
{
sumall = sumall + start;
++start;
}
std::cout << "The sum is: " << sumall << std::endl;
return 0;
}
You need to check each number in the range with modulo.
For ex:
if( start%2 == 0 ) // even
{
evenSum+=start;
}
else // Odd
{
oddSum+=start;
}
That will do the job.
You can test for odd numbers by anding with 1.
if ((start & 1) == 0)
evenSum += start;
else
oddSum += start;
Small note when talking to mathematicians: don't use modulo and modulus interchangeably (even though wikipedia says they are the same):
modulo is % for positive numbers.
modulus is the abs function.

Does this program have a limit?

I am having a problem with this code. Although it should say that this number is not prime, as i put a ridiculously large number that i know to be nonprime (252345435465, or even 1000000000000 as an example), it states that the number is prime.
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int n;
int i;
int prime = true;
cout << "Type in a number and press ENTER: ";
cin >> n;
i = 2;
while (i <= sqrt(n)) {
if (n % i == 0) {
prime = false;
break;
}
i++;
}
if (prime)
cout << "The number is prime" << endl;
else
cout << "The number is NOT prime" << endl;
system("PAUSE");
return 0;
}
Is there something I'm doing wrong?
The values you are putting in are too big for an int to hold. They are overflowing the 32 bit limit of a signed int (-2147483648 through 2147483647).
First, to avoid including the non-standard header <stdafx.h>, just turn off precompiled headers in your Visual C++ project (right click the project, then properties).
The main problem is that you're inputting values too large for the int type.
To detect that, simply check the state of the stream after the input operation:
#include <iostream>
#include <stdlib.h> // EXIT_FAILURE
#include <cmath>
using namespace std;
int main() {
int n;
int i;
int prime = true;
cout << "Type in a number and press ENTER: ";
cin >> n;
if( cin.fail() )
{
cout << "Sorry, that's not a valid `int` number." << endl;
return EXIT_FAILURE;
}
i = 2;
while (i <= sqrt(n)) {
if (n % i == 0) {
prime = false;
break;
}
i++;
}
if (prime)
cout << "The number is prime" << endl;
else
cout << "The number is NOT prime" << endl;
system("PAUSE");
return 0;
}
A 32-bit signed int can take a range of values between –2,147,483,648 to 2,147,483,647. Your number is too large for that range.
Either use a more suitable variable type, or only input numbers which are within range for the variable you are using.
See this answer for more information on C++ data types and their ranges.