C++ Program Finding Prime Numbers and Timing itself -
i trying write c++ program finds n prime numbers , times itself. have done in 5 other languages using logic. reason, code nothing. using code blocks compiler. causes code not work , how can fix it? not familiar c++ trivial.
#include <iostream> #include <math.h> int main(){ int n=10; int b=new int[n]; int c=0; int d=2; while(c<n){ bool e=true; for(int i=0;i<c;i++){ if(d<sqrt(b[i])){ break; } if(d%b[i]==0){ e=false; break; } } if(e){ b[c]=d; c++; } d++; } for(int i=0;i<c;i++){ cout << b[i]+"\n" << endl; } }
several issues:
int b=new int[n]; //^^compile error
should be
int* b=new int[n]; //also need initialize array b
meanwhile:
if (d<sqrt(b[i]))
you should initialize b
before try access it.
besides:
cout << b[i]+"\n" << endl;
edit: @daniel fischer, compile std::
added before cout
, endl
, result in undefined behavior. try:
cout << b[i] << endl;
if want print b[i]
s only.
additionally, inside while
loop, need increment c
after b[c] = d
, otherwise, going element same index again , again.
Comments
Post a Comment