How to make a function that calls the next prime number every time I call it?
Here's what I've got:
#include <iostream>
#include <cmath>
void prime();
using namespace std;
int main()
{
void prime();
}
bool isPrime(int integer)
{
int x;
int br = 0;
for (x = 1; x < integer; x++) {
if (integer % x == 0) {
br++;
}
}
if (br == 1) {
cout << " The number " << integer << " is prime " << endl;
}
else if (br > 1) {
cout << " The number " << integer << " is not prime " << endl;
}
}
void prime(){
for (int x = 2;x<1000;x++){
isPrime(x);
}
}
Nothing is displayed when I run it.
Edit: Here I added the main function...
int main()
{
void prime();
}
void prime(); is a function declaration. It has no effect; the function is not called. You must call the function:
int main()
{
prime();
}
And then there's another big problem. Your isPrime function doesn't return anything. Add a return statement to it:
return br == 1;
If you do not intend for the function to return anything (and your code currently doesn't use the returned value, so this may indeed be your intention), then make it a void function.
isPrime is boolean function is expecting to return true or false, there is no return in your code. Make it a void if you just want to "cout" the number on the console.
The main issue with your code is that you are not returning anything from your isPrime function (which should give back a boolean value).
For that you can rewrite your code as:
bool is_prime(int integer) {
if (integer < 2) return true;
auto range = boost::irange(2, integer);
auto pred = [integer](auto i) { return integer % i == 0; };
return find_if(range, pred) == std::end(range);
}
Live demo
Second, your main:
int main()
{
void prime();
}
Is really just declaring the function prime. In order to call it you can write:
void prime();
int main() {
prime();
}
Related
I have the following code
#include<iostream>
using namespace std;
int rec(int p)
{
if(p==0)
return 0;
rec(p-1);
if(p==3)
exit(0);
cout<< "The value of p is "<< p<<endl;
return 0;
}
int main()
{
int x=rec(5);
cout<<"Printing from main"<<endl;
return 0;
}
I want to print only for p==1 and p==2 in the recursive function and then return to the main function and print the line Printing from main. What is the proper way to do so?
If you want to return after printing 1 or 2, would terminating the recursion work? In that case, you can use the code below, and stop the recursion in case you encounter 1 or 2.
Also, as the code in the question is, x is not used.
#include<iostream>
using namespace std;
int rec(int p)
{
if (p <= 0) {
return 0;
} else if (p == 1 || p == 2) {
cout << "The value of p is " << p << endl;
return p;
} else {
return rec(p - 1);
}
}
int main()
{
int x{rec(5)};
cout << "Printing from main" << endl;
return 0;
}
The return value should be 7 and is calculated correctly in the gcd function.
So I return the value in line 7.
But in the main function, when i printed out the return value, it is 3.
I don't know why.
int gcd(int p, int q)
{
if(p<q){gcd(q,p);}
if(q==0)
{
cout<<"p: "<<p<<endl; //This prints out 7
return p;
}
else gcd(q,p%q);
}
int main()
{
int n;
int count=0;
cin>>n;
while(n--)
{
count++;
cout<<"Pair #"<<count<<": ";
string input,input2;
cin>>input>>input2;
int sum1=0,sum2=0;
int g;
for(int i=0;i<input.size();i++)
{
if(input[i]-'0'==1)
sum1+=pow(2,input.size()-1-i);
}
for(int i=0;i<input2.size();i++)
{
if(input2[i]-'0'==1)
sum2+=pow(2,input2.size()-1-i);
}
cout<<sum1<<" "<<sum2<<endl;
g = gcd(sum1,sum2);
cout<<"g: "<<g<<endl; //but this print out 3
}
}
Recursive functions work exactly like non-recursive functions, including how calling a function does not automagically and immediately return the result of that function call.
You need to return a value on every execution path or your code will have undefined behaviour;
int gcd(int p, int q)
{
if (p < q)
{
return gcd(q, p);
}
if (q == 0)
{
cout << "p: " << p << endl;
return p;
}
else
return gcd(q, p % q);
}
(A decent compiler should be able to warn you about those missing returns. Find out how to enable such warnings.)
So I'm supposed to use the Binary Search template function to read elements from a file to an array and then allow the user to search for an element if it's in the array. The problem is that whenever I search for a number, it gives me a "not found" even if the element does exist in the file. I know it's better to leave the template functions in the header file, but since I had no idea how to sort the file so the binary search would work I put the functions in the main program to make it less confusing. think the problem is in the main() or the sort function, but to my limited knowledge I can't figure out where exactly and how to fix it.
This is my code:
#include <iostream>
#include <string>
#include <conio.h>
#include <fstream>
using namespace std;
template<class elemType>
class orderedArrayListType
{
public:
static const int length = 20;//Const length of array you can change it accordingly
int list[length];
int binarySearch(elemType const&)const;
};
template<class elemType>
int orderedArrayListType<elemType>::binarySearch(const elemType& item) const
{
int first = 0;
int last = length - 1;
int mid;
bool found = false;
while (first <= last && !found)
{
mid = (first + last) / 2;
if (list[mid] == item)
found = true;
else if (list[mid] > item)
last = mid - 1;
else
first = mid + 1;
}
if (found)
return mid;
else
return -1;
}
void main()
{
std::fstream numberFile("text.txt", std::ios_base::in);
orderedArrayListType<int> object;
int number=0, a;
int i = 0;
int numberToSearch;
while (numberFile >> a)
{
object.list[i] = number;//Initalizing the array
i++;
}
cout << "Enter Number you want to search" << endl;
cin >> numberToSearch;
int output = object.binarySearch(numberToSearch);//Make search
if (output>0)
{
cout << "Element found at Index: " << output << endl;
}
else
{
cout << "Element not Found" << endl;
}
}
And these are the contents of the text.txt file:
1 2 3 4 5 6 7 8 9 10
Thanks in advance!
Here you are setting all elements of the list to 0:
while (numberFile >> a)
{
object.list[i] = number;//Initalizing the array
i++;
}
Instead, you should fill in the numbers read from the file:
while (numberFile >> a)
{
object.list[i] = a;//Initalizing the array
i++;
}
Then, it would be better if you would use the template parameter for the list, because else the template will only work for int:
template<typename elemType>
class orderedArrayListType
{
public:
static const int length = 20;//Const length of array you can change it accordingly
elemType list[length];
int binarySearch(elemType const&)const;
};
template<typename elemType>
int orderedArrayListType<elemType>::binarySearch(const elemType& item) const
{
int first = 0;
int last = length - 1;
elemType mid;
....
Problem is not in the binary search function but with :
while (numberFile >> a)
{
object.list[i] = number;//Initalizing the array
i++;
}
number is always 0.
One advice , change :
mid = (first + last) / 2;
to
mid=first + (last-first)/2
It avoids overflow. It's always a good programming practice to look for these cases as well.
Thanks to those tips I was able to run the program correctly. Here is the edited main() program code to make it extra clear for anyone who might stumble upon any problems with such a program.
void main()
{
std::fstream numberFile("text.txt", std::ios_base::in);
orderedArrayListType<int> object;
int number=0, a;
int i = 0;
int numberToSearch;
while (numberFile >> a)
{
object.list[i] = a;//Initalizing the array
i++;
}
cout << "Enter Number you want to search" << endl;
cin >> numberToSearch;
int output = object.binarySearch(numberToSearch);//Make search
if (output>0)
{
cout << "Element found at Index: " << output << endl;
}
else
{
cout << "Element not Found" << endl;
}
}
Note that the change was only made to the part where the array is initialized as user (alain) advised:
while (numberFile >> a)
{
object.list[i] = a;//Initalizing the array
i++;
}
I know this question has been asked before, but I didn't find any promising answers, and the cases were different from mine.
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <type_traits>
template<class getN>
getN getNum(std::string prompt, std::function<bool(getN)> condition, std::string error)
{
std::cerr << prompt;
std::string strNum;
std::getline(std::cin, strNum);
try
{
size_t pos;
getN num;
if (std::is_integral<getN>::value == true)
{
num = static_cast<getN>(stoi(strNum, std::addressof(pos)));
}
else
{
num = static_cast<getN>(stof(strNum, std::addressof(pos)));
}
if (all_of(strNum.begin() + pos, strNum.end(), [](char c) { return isspace(c); }) && condition(num))
{
return num;
}
}
catch (std::exception) {}
std::cerr << error;
return getNum(prompt, condition, error);
}
void fillArray(float *arr, int size)
{
std::cout << "\nFill the array:\n";
for (int i = 0; i < size; i++)
{
std::cout << "arr[" << i + 1 << "]=";
arr[i] = getNum<float>("", [](bool num) {return num != 0.0f; }, "Bad input! Try again: ");
}
}
int main()
{
int size;
std::cout << "Size: ";
std::cin >> size;
float *arr = new float[size];
fillArray(arr, size);
delete[] arr;
std::cin.ignore();
std::cin.get();
return 0;
}
Calling the function with an "int" like the very last statement, doesn't give me any errors or warnings, but calling it with "float" like the fillArray function throws the C4800 at me.
You have declared your getNum function:
getN getNum(std::string prompt, std::function<bool(getN)> condition, std::string error)
to take a function of that returns a bool value from condition.
And then call it with this:
arr[i] = getNum<float>("", [](float num) {return num; }, "Bad input! Try again: ");
which passes a float return value. Whilst the compiler CAN convert a float to a bool, it is not as efficient as taking the bool return value from the function. So use:
[](float num) -> bool {return num != 0.0f; }
instead, it should not complain.
Also, in future, it would be better to produce a COMPLETE program that can be compiled (that is, has all the #include required, as well as the main function to exercise the code), that way someone can JUST take your code, compile it and make some slight changes to fix the problem, rather than having to guess what headers are required and how you intend the things you posted to be used.
I'm trying to create a program that takes a polynomial function from the user, counts the number of terms it has, creates an array large enough to store all of the terms, and then stores the terms there. The problem is that I'm not quite sure how to add a private class variable (or more specifically, a string array) AFTER the program determines how the large the function is. I need this string array to be a private class variable because I want to be able to access its contents through other class methods to do things like, for example, cout each of the function terms.
main.cpp:
#include <iostream>
#include <string>
#include "Function.h"
using namespace std;
int main()
{
Function func1;
func1.coutFuncTerms();
func1.coutFunc();
return 0;
}
Function.h:
#ifndef FUNCTION_H
#define FUNCTION_H
#include <iostream>
#include <string>
#include "Function.h"
using namespace std;
class Function
{
public:
Function();
~Function();
void removePlus(string*);
void removeWhitespace(string*);
void setFuncTerms();
void splitTerms();
void coutFuncTerms();
void coutFunc();
void coutTerms(string);
protected:
private:
string func;
int funcTerms;
};
#endif
Function.cpp:
#include <iostream>
#include <string>
#include "Function.h"
using namespace std;
// Function Constructor
//
// Stores a function inputted by the user
// Adds a null character ('\0') to the end of a string
// Erases a redundant '+' sign at the beginning of a string if there's one there
// Erases any whitespace characters in a string
// Stores the number of terms in the function
Function::Function()
{
getline(cin, func);
setFuncTerms();
//splitTerms();
}
Function::~Function()
{
}
// removePlus Function
//
// Erases a redundant '+' sign at the beginning of a string if there's one there
void Function::removePlus(string* func)
{
if(func->at(0) == '+')
{
func->erase(0, 1);
}
}
// removeWhitespace Function
//
// Erases any whitespace characters in a string
void Function::removeWhitespace(string* func)
{
for(int x = 0; unsigned(x) < func->length() - 1; x++)
{
while(func->at(x) == ' ' || func->at(x) == '\t')
{
func->erase(x, 1);
}
}
}
// setFuncLength Function
//
// Finds the number of terms in a Function object's 'func' variable
// Assigns this number to the object's 'funcLength' variable
void Function::setFuncTerms()
{
funcTerms = 0;
for(int funcTerm = 0; unsigned(funcTerm) < func.length(); funcTerm += 1)
{
bool isAPotentialTerm = false;
bool isATrueTerm = false;
if(func.at(funcTerm) == '+' || func.at(funcTerm) == '-')
{
isAPotentialTerm = true;
}
if(isAPotentialTerm == true)
{
for(int newFuncTerm = funcTerm + 1; unsigned(newFuncTerm) < func.length(); newFuncTerm += 1)
{
if(func.at(newFuncTerm) == '+' || func.at(newFuncTerm) == '-')
{
break;
}
if(func.at(newFuncTerm) != ' ' && func.at(newFuncTerm) != '\t')
{
isATrueTerm = true;
break;
}
}
}
if(isATrueTerm)
{
funcTerms++;
}
}
}
// splitTerms Function
//
// Calls the splitTerm function for each term in 'func' according to the function array 'funcArray'
void Function::splitTerms()
{
string funcArray[funcTerms];
int tempFuncLength = 0;
for(int funcTerm = 0; unsigned(funcTerm) < func.length(); funcTerm += 1)
{
bool isAPotentialTerm = false;
bool isATrueTerm = false;
if(func.at(funcTerm) == '+' || func.at(funcTerm) == '-')
{
isAPotentialTerm = true;
}
if(isAPotentialTerm == true)
{
for(int newFuncTerm = funcTerm + 1; unsigned(newFuncTerm) < func.length(); newFuncTerm += 1)
{
if(func.at(newFuncTerm) == '+' || func.at(newFuncTerm) == '-')
{
break;
}
if(func.at(newFuncTerm) != ' ' && func.at(newFuncTerm) != '\t')
{
isATrueTerm = true;
break;
}
}
}
if(isATrueTerm)
{
string temp;
for(; unsigned(funcTerm) < func.length() && func.at(funcTerm) != '+' && func.at(funcTerm) != '-'; funcTerm += 1)
{
funcArray[tempFuncLength].append(1, func.at(funcTerm));
}
tempFuncLength++;
}
}
for(int x = 0; x < funcTerms; x++)
{
cout << "Term " << x + 1 << " is: " << funcArray[x] << endl;
}
}
void Function::coutFuncTerms()
{
cout << "Terms: " << funcTerms << endl;
}
void Function::coutFunc()
{
cout << "Function: " << func << endl;
}
void Function::coutTerms(string funcArrayTerm)
{
/*for(int x = 0; x < funcLength; x++)
{
cout << "Term " << x << " is: " << funcArray[x] << endl;
}*/
//cout << funcArray[0] << endl;
}
I highly recommend you change your design.
A function is a container of terms. So let's define a term:
A term minimally has a coefficient and an exponent:
struct Fundamental_Term
{
double coefficient;
int exponent;
};
If your function is only in terms of one variable, all you need is the Fundamental_Term. Otherwise, you need to have the base variable name:
struct Term_With_Base
: public Fundamental_Term
{
std::string variable_name;
};
Note: if you can't use inheritance, copy the member variables of Fundamental_Term into Term_With_Base.
Remember a function is a collection or container of terms. Assuming a function with multiple bases, we can declare:
struct Function
{
std::vector<Term_With_Base> terms;
};
Evaluation of Terms
To evaluate a function, f(x), all terms must be evaluated and their results summed.
This decomposes into two requirements: 1) Terms must have an evaluation method; 2) The function class must have an evaluation method that sums the terms.
So, we add an evaluation function to the base class:
struct Fundamental_Term
{
double coefficient;
int exponent;
double evaluate(double value)
{
return coefficient * pow(value, exponent);
}
};
struct Function
{
std::vector<Term_With_Base> terms;
double evauate(double value)
{
const unsigned int quantity = terms.size();
double result = 0.0;
for (unsigned int i = 0; i < quantity; ++i)
{
result = result + terms[i].evaluate(value);
}
return result;
}
};
When creating a function from a string, a preference is to create a constructor of Fundamental_Term that takes a string parameter. The term object should read its coefficient, variable name and exponent, not the Function container.
For more examples, search StackOverflow for "c++ parse term evaluation".
Edit 1: Inserting terms
One method to insert terms, is to have a method in the term data structure that loads a term from a string:
bool
Fundamental_Term ::
load_from string(const std::string& input,
unsigned int & start_position)
{
bool term_is_valid = false;
// Parse the string and load appropriate fields.
// Set the start position to the first position after the valid term.
// Set term_is_valid to true if the term has valid syntax.
return term_is_valid;
}
The Function object would have a member to load terms from a string.
bool
Function ::
load_terms_from_string(const std::string& input)
{
Term_With_Base term;
unsigned int position_in_string = 0;
bool term_is_valid = true;
while (term_is_valid && (position_in_string < input.size()))
{
term_is_valid = term.load_from_string(input, position_in_string);
if (term_is_valid)
{
terms.push_back(term);
}
}
}
The std::vector used to contain the terms will expand as necessary with each additional term that is parsed. The loop will terminate when the string is parsed or there is an invalid term.