简体   繁体   中英

No response of a find prime number program

I was stuck in my programming assignment This assignment is using a bool array to find prime number between 2 to N The method of it is all prime number "index" will be set on true and other will be set on false,so finally it just print out the true index Here is my code

#include <iostream>
#include <ctime>
using namespace std;

int main(){
    int n,i;
    int count = 0;
    cout << "Enter the value of n: ";
    cin >> n;
    bool* prime = new bool[n];
    for (i=0;i<=n;i++)
        prime[i] = true;
    for (i=2;i<=n;i++)
        if (prime[i])
            for (int j=n;j=i;j--)
                if (j%i == 0)
                    prime[j] = false;
    cout << "Prime numbers: ";
    for (i=2;i<=n;i++)
        if(prime[i])
            {cout << i <<", ";
             count++;}
    cout << count <<" primes found.";


    //hold the windows
    system("pause");
    return 0;
}

The problem of it is after I input the value of N, the program is no response and didn't show any thing out.

Just skimming over your code, I can see that you have used the wrong operator on this line:

for (int j=n;j=i;j--)

Where j=i should be j==i . j=i uses the assignment operator ( = ) rather than the comparison operator ( == ), and will always evaluate to true if i is non-zero, thus creating an infinite loop - meaning no output, etc


Side note

You may want to look into bounds-checking for n . What if the user enters a negative number? bool* prime = new bool[n]; would try to produce a negative-sized array, which is not possible (unless the number is converted into an unsigned value, in which case you'd have a huge array of booleans)

I see a bug when looking at the initialization of the array:

bool* prime = new bool[n];

The elements in prime will be from 0 to n-1. Then, there`sa loop setting the values to true. At some point, i == n:

for (i=0;i<=n;i++)
    prime[i] = true;

When i == n, you have written too far in the array. This might overwrite the return address.

Programmers often try to create arrays that are the exact size they need. Unless there`sa lot of storage being needed, I like to create arrays a little bit too big. This reduces the chances of an buffer overflow bug causing an exploit in my code.

bool* prime = new bool[n + 20];

You`d be surprised how many times that practice will save you time.

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