Prime number finding program using bool values - c++

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.

Related

Total number of odd/even numbers

Hello I'm trying to display only the amount of odd/even numbers for the digits entered. I've tried multiple methods but failed to find any solution. This is the problem and what I have so far.
Write a program that allows the user to enter 10 separate whole numbers. After accepting these 10 numbers from the user, the program should display output to the user informing them how many of the numbers entered were odd numbers and how many were even numbers.
#include <iostream>
using namespace std;
int main() {
char even, odd;
int number;
for(int i = 1;i<=10;i++) {
cout << "Enter Number " << i << ":" ;
i=i+0;
cin >> number ;
}
if (number%2==0){
number = even;
}
cout<< "You entered:\n";
cout << "Odd Numbers: " << odd << endl;
cout << "Even Numbers: " << even << endl;
return 0;
}
There are a few things in your code that do not look right.
for(int i = 1; i <= 10; i++)
{
cout << "Enter Number " << i << ":";
i = i + 0;
cin >> number;
}
What are you hoping to accomplish with the line i = i + 0? Your loop will work just fine without it.
char even, odd;
Technically, since char is a numeric type, you may keep track of the number of even and odd numbers encountered by keeping track of them. However, you aren't doing that.
The statement:
if (number%2==0){
number = even;
}
Is saying that if the input number is even, assign the current value of char even to number. However, this doesn't make sense, since you never stored a value in even earlier. Also, you're doing this outside the loop, so effectively only the last of the 10 values read into number would ever be counted in your calculations (if you had that done correctly).
What you should do:
int even = 0, odd = 0;
for(...)
{
// read input into "number"...
if(number % 2 == 0)
{
even++;
}
else
{
odd++;
}
}

Ignoring invalid input from a count and average

The program requires the user to input numbers and when finished to exit the loop by entering a negative number. The program will then output the average of the numbers and the count of the numbers. The negative number should be removed from the series though. So if we have three numbers and exit on the (fourth) negative number, the average will only be of the three numbers and not include the negative number. Neat, I somehow made that work. Now, I need to expand upon this to make it so that the input is verified to be an integer and less than 100 also using a Boolean equation. It is at this point that I cannot determine how to exclude the erroneous input from the results.
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
float inScore= 1;
float sumScore= 0.0;
int scoreCount= 0;
float avgScore= 0.0;
bool moreNumbers = true;
bool notNumbers = true;
for ( inScore =1; inScore >=1; inScore++) //for loop some kind of blackmagic not really sure about this right now
{
cout << "Please enter grades (enter a negative integer to exit): ";
cin >> inScore;
if (!cin || inScore > 100)
{
notNumbers = false; //boolean to ignore non integers or numbers greater than 100
cin.clear();
cin.ignore(256, '\n');
scoreCount--;
cout << "Invalid number!" << endl;
} //something is wrong in this section and I can't get it to ignore the invalid inputs
else if (inScore < 0)
{
moreNumbers = false;
} //breaks the loop upon a negative number being entered
else
sumScore+=inScore;
scoreCount++;
}
avgScore = (sumScore+=inScore)/(scoreCount-1);
cout << "Number of Grades: " << scoreCount-1 << endl; //number of entries
cout << "Average: " << avgScore << endl; // average grade except I cannot figure out how to remove negative number from the array
return 0;
}

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

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

Create a program that takes as input a string of digits and outputs the sum of the even and the sum of the odd digits

Create a program that takes as input a string of digits and outputs
the sum of the even and the sum of the odd digits. This program is in
C++
NOTE: It is recommended that you use a "for" loop to iterate over the
sting of digits. HINT: Use the modulus operator to determine even or
odd digits.
A clever method of converting a "char" to an "int" is as follows link:
char a = '4';
int ia = a - '0';
The above code takes advantage of the character's position in the
ASCII table to convert it to an integer.
Below is the code I have so far:
int main() {
int sumOdd = 0; // For accumulating odd numbers, init to 0
int sumEven = 0; // For accumulating even numbers, init to 0
int digits; // Sum from 1 to this upperbound
// Prompt user for an upperbound
cout << "Please enter a string comprised ONLY of digits:" << endl;
cout << endl;
cin >> digits;
// Use a while-loop to repeatedly add 1, 2, 3,..., to the upperbound
int number = 1;
while (number <= digits) {
if (number % 2 == 0) { // Even number
sumEven += number; // Add number into sumEven
} else { // Odd number
sumOdd += number; // Add number into sumOdd
}
++number; // increment number by 1
}
// Print the results
cout << "The string of digits \"" << digits << "\""
<< " contained "
<< "characters." << endl;
cout << "The sum of the even digits is: " << sumEven << endl;
cout << "The sum of the odd digits is: " << sumOdd << endl;
return 0;
}
This is my output compared to the output I need
Input:
1234567890
Output:
Please enter a string comprised ONLY of digits:
The string of digits "1234567890" contained characters.
The sum of the even digits is: -380436870
The sum of the odd digits is: -997720815
Expected output
Please enter a string comprised ONLY of digits:
The string of digits "1234567890" contained 10 characters.
The sum of the even digits is: 20
The sum of the odd digits is: 25
Overall I'm having trouble counting the input and getting the correct formula for my even and odd numbers. Any help is appreciated thank you so much!
A simple method is to keep the number in text form:
std::string number_as_text;
cout << "Enter number: ";
cin >> number_as_text;
This allows you to check each digit for even or odd:
const size_t length = number_as_text.length();
for (size_t i = 0; i < length; ++i)
{
char digit_character = number_as_text[i];
if (isdigit(digit_character))
{
if (digit_character % 2 == 0)
{
// digit is even
}
else
{
// digit is odd
}
}
}
If you don't like isdigit(), you can replace with:
if ((digit_character >= '0') && (digit_character < '9'))
An important note is that there is a difference between the textual representation of digits and the internal, numeric, representation of digits.
Edit 1: % on char type
The char data type is an integer. The remainder operator, %, works on integer types. Thus you can use % on char types.
Note: this operation assumes that the character mapping of '0' is an even integer and the other digits are successive in values.
Read the inputs in a string field and not an integer as -
std::string digits;
Then, just run a valid loop to find out the sum of the even digits and the odd digits -
for(int i=0; i<digits.length(); i++){
int digit = digits[i]-'0';
if(digit % 2 == 0)
sumEven+=digit;
else
sumOdd+=digit;
}
Below is a running piece of code.
// Example program
#include <iostream>
#include <string>
using namespace std;
int main() {
int sumOdd = 0; // For accumulating odd numbers, init to 0
int sumEven = 0; // For accumulating even numbers, init to 0
std::string digits; // Sum from 1 to this upperbound
// Prompt user for an upperbound
cout << "Please enter a string comprised ONLY of digits:" << endl;
cout << endl;
cin >> digits;
// Use a while-loop to repeatedly add 1, 2, 3,..., to the upperbound
int number = 1;
for(int i=0; i<digits.length(); i++){
int digit = digits[i]-'0';
if(digit % 2 == 0)
sumEven+=digit;
else
sumOdd+=digit;
}
// Print the results
cout << "The string of digits \"" << digits << "\""
<< " contained "
<< "characters." << endl;
cout << "The sum of the even digits is: " << sumEven << endl;
cout << "The sum of the odd digits is: " << sumOdd << endl;
return 0;
}
You got it wrong you are supposed to do sum of 1+3+5+7+9 and sum of 2+4+6+8+0. What are you doing instead is sum of all even numbers smaller than 1234567890 and sum of odd numbers smaller than 1234567890.
Maybe consider instead of getting all numbers in string by cin >> digits read it from input by characters one by one.
Check this code it reads characters from input and spits them back.
#include<iostream>
using namespace std;
int main() {
cout << "Please enter a string comprised ONLY of digits:" << endl;
cout << endl;
char one;
while ( true ) {
cin >> one;
// here will come your part with deciding even / odd and counting instead of pritnting out.
cout << " " << one;
if ( cin.peek() == '\n' ) { break; }
}
return 0;
}
And now it's your turn to put it together.
Use std::getline to read all digits into a std::string:
std::cout << "Enter string of numbers: " << std::endl;
if (std::string numbers; std::getline(std::cin, numbers)) {
/* ... */
}
Note the use of conditional-if above from the upcoming C++1z standard.
Then, you could make use of std::pair to neatly accumulate the odds and evens like this:
std::pair odd_even{0, 0};
for (auto c : numbers) {
(c % 2 ? std::get<0>(odd_even) : std::get<1>(odd_even)) += c - '0';
}
Live example
This one logically should work
for(int i=0; i<digits.lenght; i++){
if(digits[i] % 2 == 0)
sumEven+=digits[i];
else
sumOdd+=digits[i];
}

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.