Prime number function C++ - c++

I'm using filestreams, reading integers into an infile then reading those positive into an array directed to an outfile. I bubble sort the array and am required to find the average, variance, standard deviation, and prime numbers. I'm having trouble with my prime numbers function, it is not streaming anything into my file at all. Photo of my terminal here. It's also miscalculating my average. I've taken out my sorting and get data functions so it doesn't look messy.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cmath>
using namespace std;
const int MAX = 30;
void getVariance(int[], int);
bool isPrime(int[], int);
double average(int[], int);
int main()
{
string inputfilename, outputfilename;
ifstream infile;
ofstream outfile;
int prime, n, sum =0, posnumbers[MAX], countp=0, countn=0\
;
double variance, stdv, avg=0;
cout << "Please enter the name of the input file: ";
cin >> inputfilename;
infile.open(inputfilename.c_str());
cout << "Please enter the name of the output file: ";
cin >> outputfilename;
///////////////////////postive ////////////////////////////
outfile.open(outputfilename.c_str());
if(!infile)
cout << "file not open for input" << endl;
else
{
prime = isPrime(posnumbers, n);
outfile << "=======================" << endl << endl;
outfile << "Positive #'s in the File" << endl;
for (int i=0; i<n; i++)
{
if (posnumbers[i]>=0)
{
countp++;
sum = sum + posnumbers[i];
outfile << posnumbers[i] << endl;
if (posnumbers[i] == prime)
outfile << posnumbers[i] << endl;
}
}
outfile << "average " << sum/n << endl;
outfile << "variance " << variance << endl;
///////////////////////// functions/////////////////////
bool isPrime(int posnum[], int n)
{
for (int i=2; i<=posnum[n]/2; i++)
if (posnum[n] % i ==0)
return false;
else
return true;
}
double average(int posnum[], int n)
{
double sum = 0.0;
for (int i=0; i<n; i++)
{
sum += posnum[n];
}
return sum / n;
}

bool isPrime(int posnum[], int n)
{
for (int i=2; i<=posnum[n]/2; i++)
if (posnum[n] % i ==0)
return false;
else
return true;
}
This will not work. The reason is that you immediately return true when the number is not divisible. For example, if posnum[n] is, let's say, 3, then your modulo check will fail and you are going to return true immediately, without checking all the other numbers that could potentially be divisors.
Furthermore, isPrime is currently checking only a single number for primality, but that isn't reflected in the calling code.
prime = isPrime(posnumbers, n);
Since isPrime returns bool, prime is now either 0 or 1.
if (posnumbers[i] == prime)
outfile << posnumbers[i] << endl;
This means that that line will only output all numbers being 0 or 1, depending on the value of prime. You should call isPrime for every element of posnumbers instead and print it if it returns true.
For isPrime, try the following:
bool isPrime(int posnum[], int n) {
for (int i = 2; i <= posnum[n] / 2; ++i) {
if (posnum[n] % i == 0) {
return false;
}
}
return true;
}

Related

Function that finds prime numbers between two intervals

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;
}

display all the Prime numbers which are less than certain number

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;
}

use of undeclared identifier 'data' C++

"Write a function, named sums(), that has two input parameters; an array of floats; and an integer,
n, which is the number of values stored in the array. Compute the sum of the positive values in the array
and the sum of the negative values. Also count the number of values in each category. Return these four
answers through output reference parameters.
Write a main program that reads no more than 10 real numbers and stores them in an array. Stop reading numbers when a 0 is entered. Call the sums() function and print the answers it returns. Also compute and print the average values of the positive and negative sets."
#include <iostream>
using namespace std;
void sums(float data[], int count, float& posSum, int& posCnt, float& negSum, int& negCnt);
double input(double UserInput);
int main()
{
float data[10];
int count = 10 ;
double UserInput = 0;
float posSum=0.0, negSum=0.0; //sum of positives and negatives
int posCnt =0, negCnt=0; // count of postive and negatives
input(UserInput);
sums(data, count, posSum,posCnt, negSum, negCnt);
cout << "Positive sum: " << posSum << endl;
cout << "Positive count:" << posCnt << endl;
cout << "Negative sum: " << negSum << endl;
cout << "Negative count:" << negCnt << endl;
return 0;
}
double input(double UserInput) {
for(int i = 0; i < 10; i++){
cout << "Enter a real number or '0' to stop: " ;
cin >> UserInput;
if(UserInput == 0)break;
data[i] = UserInput;
}
return UserInput;
}
void sums(float data[], int count, float& posSum, int& posCnt, float& negSum, int& negCnt){
int i;
for(i = 0; i < count; i++){
if(data[i] > 0){
posCnt += 1;
posSum += data[i];
}
else{
negCnt += 1;
negSum += data[i];
}
}
}
It gives me an error when trying to compile it saying "use of undeclared identifier 'data'" on line 32 in the input function.
It is because the data is not declared in the function input, you should use a float pointer.
void input(float *data)
{
float UserInput;
for (int i = 0; i < 10; i++)
{
cout << "Enter a real number or '0' to stop: ";
cin >> UserInput;
if (UserInput == 0)break;
data[i] = UserInput;
}
return;
}
int main()
{
float *data;
data = (float*)malloc(10 * sizeof(float));
input(data);
cout << data[0];
free(data);
system("pause");
return 0;
}
This should be an accurate example. Good Luck with your following homework.

Not taking the input

I want to write a program that only takes odd numbers, and if you input 0 it will output the addition and average, without taking any even number values to the average and the addition. I'm stuck with not letting it take the even values..
Heres my code so far:
int num = 0;
int addition = 0;
int numberOfInputs = 0;
cout << "Enter your numbers (only odd numbers), the program will continue asking for numbers until you input 0.." << endl;
for (; ;) {
cin >> num;
numberOfInputs++;
addition = addition + num;
if (num % 2 != 0) {
//my issue is with this part
cout << "ignored" << endl;
}
if (num == 0) {
cout << "Addition: " << addition << endl;
cout << "Average: " << addition / numberOfInputs << endl;
}
}
Solution of your code:
Your code doesn't working because of following reasons:
Issue 1: You adding inputs number without checking whether it's even or not
Issue 2: If would like skip even then your condition should be as follow inside of the loop:
if (num%2==0) {
cout << "ignored:" <<num << endl;
continue;
}
Solving your issues, I have update your program as following :
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num = 0;
int addition = 0;
int numberOfInputs = 0;
cout << "Enter your numbers (only odd numbers), the program will continue asking for numbers until you input 0.." << endl;
for (; ;) {
cin>> num;
if (num%2==0) {
cout << "ignored:" <<num << endl;
continue;
}
numberOfInputs++;
addition = addition + num;
if (num == 0) {
cout << "Addition: " << addition << endl;
cout << "Average: " << addition / numberOfInputs << endl;
break;
}
}
}
#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
int number;
int sum=0;
int average=0;
int inputArray[20]; // will take only 20 inputs at a time
int i,index = 0;
int size;
do{
cout<<"Enter number\n";
cin>>number;
if(number==0){
for(i=0;i<index;i++){
sum = sum + inputArray[i];
}
cout << sum;
average = sum / index;
cout << average;
} else if(number % 2 != 0){
inputArray[index++] = number;
} else
cout<<"skip";
}
while(number!=0);
return 0;
}
You can run and check this code here https://www.codechef.com/ide
by providing custom input

Reversing a number C++

Looking for some advice here on what I'm getting wrong. Everything in my main should be fine and left unchanged. My problem is in my reverse function. It's printing the reversed number right before the cout statement of "The number is" instead down below where it should be. I spent awhile trying to fix but can't come up with a solution.
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
const int NUM_VALS = 10; //the maximum number of values to use
int reverse(int num);
bool isPrime(int num);
int main()
{
int number, //Holds the random number that is manipulated and tested
loopCnt; //Controls the loop
//set the seed value for the random number generator
//Note: a value of 1 will generate the same sequence of "random" numbers every
// time the program is executed
srand(1);
//Generate 10 random numbers to be manipulated and tested
for( loopCnt = 1; loopCnt <= NUM_VALS; loopCnt++ )
{
//Get a random number
number = rand();
//Display the sum of adding up the digits in the random number, the reversed
//random number, and whether or not the number is palindromic or a prime number
cout << "The number is " << number << endl
<< "----------------------------------------" << endl
// << "Adding the digits result" << setw(16) << sumDigits( number ) << endl
<< "Reversing the digits result" << setw(13) << reverse(number) << endl
// << "Is the number a palindrome?" << setw(13) << (isPalindrome(number)? "Yes" : "No") << endl
// << "Is the number prime?" << setw(20) << (isPrime(number)? "Yes" : "No") << endl
<< endl << endl;
}
return 0;
}
int reverse(int num)
{
int quo, rem;
quo = num;
while (quo != 0)
{
rem = quo % 10;
cout << rem;
quo /= 10;
}
}
bool isPrime(int num)
{
int i;
if (num % 2 == 0)
return false;
for (i = 3; i*i <= num; i+=2)
{
if (num % i == 0)
return false;
}
return true;
}
You need to have your reverse function return the number as reversed, because the return value is used in main.
You can build the reversed number by multiplying a "reversed" value by 10, then adding in the remainder:
int reverse(int num)
{
int reversed = 0;
int quo, rem;
quo = num;
while (quo != 0)
{
rem = quo % 10;
reversed = reversed * 10 + rem;
quo /= 10;
}
return reversed;
}
You can also use this method to reverse a number by taking string input and then reverse it and convert it to int.
#include <iostream>
#include<string>
using namespace std;
int reverse_num(string a)
{
string s;
for(int i=a.length()-1;i>=0;i--)
{
s+=a[i];
}
int n;
n=stoi(s);
return n;
}
int main()
{
string a;
cin>> a;
cout<<reverse_num(a);
return 0;
}