首页 > 解决方案 > 使用数组打印前 100 个素数 (C++)

问题描述

我对此很陌生,想知道我所做的是否正确。我必须使用 C++ 中的数组打印前 100 个素数。我的代码在我需要的素数旁边输出了很多数字。想知道到底出了什么问题。先感谢您。

int myPrimes[100];
int i,j,count=1,b=0;

for(i=3;i>0;++i)
{
    for(j=2;j<=i/2;++j)
    {
        if(i%j==0){//checking if composite
            b=1;//if composite, goes to the next number
            break;
        }
    }

    if(b==0)//if prime
    {
        //cout<<"\n"<<i;//print the number
        myPrimes[count]=i;
        count++;//counter goes up 1 to go to the next number
    }

    b=0;//resets b so you can run the loop again
    if(count==101)//after the counter reaches 100, exits the program
        break;
}

for(int i=0;i<=sizeof(myPrimes);i++){
  cout << myPrimes[i] << endl;
}

return 0;

我在 100 个素数之后的输出:

输出

标签: c++arrays

解决方案


使用数组打印前 100 个素数

int primes[100] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,
 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157,
 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257,
 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367,
 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 
 479, 487, 491, 499, 503, 509, 521, 523, 541};

for(int i = 0; i < 100; i++){
    cout << myPrimes[i] << endl;
}

完美的

开玩笑,不理我


提供正常答案

#include <iostream>
#include <stdio.h>
#include <stdlib.h>

bool isPrime(int number) {
    if (number <= 1) return false;

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

    return true;
}

int main() {
    const int numOfPrimes = 100;
    int primes[numOfPrimes];
    int index = 0;
    int number = 2;

    while(index < numOfPrimes) {
        if(isPrime(number)) {
            primes[index] = number;
            index++;
        }
        number++;
    }

    for(int i = 0; i < numOfPrimes; i++){
        cout << myPrimes[i] << endl;
    }

    return 0;
}

没有检查,没有编译


中间部分可以更改为:

while(index < 100) {
    if(isPrime(number++)) {
        primes[index++] = number;
    }
}

推荐阅读