#include <iostream>
#include <chrono>
#include <unistd.h>
using namespace std;
void SieveOfEratosthenes (int n)
{
bool prime[n+1], flag=true;
int counter=0, ct=0;
for (int i =0;i<n+1;i++){
prime[i]=true;
}
for (int p=2; p*p<=n; p++)
{
if (prime[p]==true)
{
for (int i=p*2; i<=n; i += p)
{
prime[i] = false;
}
}
}
// Print all prime numbers
for (int p=2; p<=n; p++)
{
if (flag)
{
auto begin=chrono::high_resolution_clock::now();
}
if (prime[p])
{
cout << p << " ";
counter+=1;
flag=false;
}
if(counter==10)
{
auto end=chrono::high_resolution_clock::now();
auto duration=chrono::nanoseconds(end-begin);
cout<<"Time elapsed:"<<duration.count();
counter=0;
flag=true;
}
}
cout<<endl;
}
int main()
{
int n;
cout<<"Type a number:";
cin>>n;
cout<<endl<<"Following are the prime numbers smaller or equal to:"<<n<<endl;
SieveOfEratosthenes(n);
return 0;
}
// Driver Program to test above function
It's an algorithm for finding prime numbers smaller to n(given from keyboard) and i want to get the time every 10 prime numbers found.I am getting operator error and it's on (end-begin).I can't understand where the error is.And i have tried to write the function in a seperate .o file but still got nothing.Any help would be much appreciated.!
begin
is defined inside an if
block, which can not be accessed by end-begin
. A simple fix is to move the definition out of the for
-loop:
decltype(chrono::high_resolution_clock::now()) begin;
// Print all prime numbers
for (int p=2; p<=n; p++)
{
if (flag)
{
begin=chrono::high_resolution_clock::now();
}
// ...
}
Note It is usually a bad idea to using namespace std
globally. Since begin
collides with std::begin
, the error message becomes intricate. If you instead write namespace chrono = std::chrono; using std::cout;
, the error would become more clear:
test.cpp: In function ‘void SieveOfEratosthenes(int)’:
test.cpp:41:53: error: ‘begin’ was not declared in this scope; did you mean ‘std::begin’?
41 | auto duration=chrono::nanoseconds(end-begin);
| ^~~~~
| std::begin