如何确定数字是否是数组中包含1000个元素的素数?

时间:2013-11-15 23:48:49

标签: c++ arrays

我正在创建一个程序,用于确定值是复合值,Prime还是Unvisited。程序忽略前两个值,因为它们是0和1,并将它们标记为I表示忽略。它不输出数字而是输出字母表示。例如:“0123456”将输出“IIPPCPC”。它需要确定最多1000的所有值。程序使用循环遍历数组并将值更改为表示它的正确字母。我很困惑我将使用什么代码循环遍历数组并将所有设置为P的值更改为复合到C的时刻。程序假设在步骤中重新遍历代码,直到所有值都是设置正确的表示。

    /*
    / Name: Ralph Lee Stone
    / Description: Uses an array to find all the prime numbers up to 1000.
    / Date: 11/13/2013
    / Project: RLStone3_HW_10
    */

    #include <iostream>
    using namespace std;

    int main()
    {
// Declares an array to print all prime numbers up to 1000.
char mychararray[1001];

// Set all array index values to 'U', which stands for unvisited.
for(int i = 0; i <= 1000; i++)
{
mychararray[i] = 'U';
}

// Set the first two elements of the array index 0 & 1 to 'I'. which stands for                ignore. 
mychararray[0] = 'I';
mychararray[1] = 'I';

//for ( int i = 0 ; i < 1001 ; i ++ )
//  cout << mychararray[i] ;
//cout << mychararray;

    //Skips the first two values, so that the first two values are skipped.
int i = 0;
while(mychararray[i] !='U')
    i++;

// Changes the all the values that are set to U to P.

for(int i = 2; mychararray[i] >= mychararray[1001];  i++)
mychararray[i] = 'P';
//i++;

    // Loops through the array again and changes all the values that are set to P that are composite to C.

    // Outputs the array.
for ( int i = 0 ; i < 1001 ; i ++ )
    cout << mychararray[i] ;

//Pauses the console window.
system("pause");

// returns the value 0.
return(0);
    }

3 个答案:

答案 0 :(得分:4)

这看起来很像家庭作业,所以我会跳过细节。你想要的是sieve of eratosthenes并且包含你已经知道的数字是素数并且从数组的其余部分丢弃它们的所有倍数。

答案 1 :(得分:3)

for (int i = 2; i < 1001; i++)
{
    for (int j = 2; j <= (int) sqrt(i); j++)
    {
        if (i % j == 0)
        {
            mychararray[i] = 'C';
            break;
        }
    }
}

^^对于数组中的每个数字,检查数字是否可以被从2到数字平方根的任何数字整除

for (int i = 2; i < 1001; i++)
{
    for (int j = 2; j * i < 1001; j++)
        mychararray[j * i] = 'C';
}

^^ Eratosthenes的筛子

答案 2 :(得分:0)

根据定义,1是素数,2是唯一的素数,所以,你可以这样:

bool isPrime(unsigned int number) {
    if (number == 1 || number == 2) {
        return true;
    }

    if (number % 2 == 0) {
        return false;
    }

    for (int i = 2; i < number / 2; i++) {
        if (number % i == 0) {
            return false;
        }
    }
    return true;
}

然后,你迭代你的数组:

char representation[SIZE];
for (int i = 0; i < SIZE; i++) {
    representation[i] = isPrime(data[i]) ? 'P' : 'C';
}