简体   繁体   中英

C++ Program Finding Prime Numbers and Timing itself

I am trying to write a c++ program that finds n prime numbers and times itself. I have already done this in 5 other languages using this logic. For some reason, this code does nothing. I am using the Code Blocks compiler. What causes this code not to work and how can I fix it? I am not very familiar with c++ so it will probably be something 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 you try to access it.

besides:

cout << b[i]+"\n" << endl;

EDIT: @Daniel Fischer, this would compile with std:: added before cout and endl , but will result in undefined behavior. try:

cout << b[i] << endl;

if you want to print b[i] s only.

Additionally, inside your while loop, you need to increment c after b[c] = d , otherwise, it is going to the element into the same index again and again.

int b should be declared as int *b

You need to add using namespace std if you want to use cout etc. without namespace prefixes. With prefixes you can do std::cout.

Also you've got an infinite loop because c is never incremented.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM