Printing prime numbers from 1 through 100

前端 未结 22 2524
无人共我
无人共我 2020-11-28 05:14

This c++ code prints out the following prime numbers: 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97.

But I don\'t think tha

22条回答
  •  生来不讨喜
    2020-11-28 05:51

    Here is my implementation of Sieve of Eratosthenes (for primes between 2 & n)

    #include 
    
    int main (){
    int n=0;
    std::cout << "n = ";
    std::cin >> n;
    std::cout << std::endl;
    
    if (n==0 || n==1){
        std::cout << "No primes in this range" << std::endl;
        return 0;
    }
    
    
    const int array_len = n-2+1;
    
    int the_int_array[array_len];
    for (int counter=2; counter <=n; counter++)
        the_int_array[counter-2]=counter;
    
    
    int runner = 0;
    int new_runner = 0;
    
    while (runner < array_len ){
        if (the_int_array[runner]!=0){
            new_runner = runner;
            new_runner = new_runner + the_int_array[runner];
    
            while (new_runner < array_len){
               the_int_array[new_runner] = 0;
               new_runner = (new_runner + the_int_array[runner]);
            }
        }
    runner++;
    }
    
    runner = 0;
    
    while (runner < array_len ){
        if (the_int_array[runner]!=0)
            std::cout << the_int_array[runner] << " ";
        runner++;
    }
    
    std::cout << std::endl;
    return 0;
    

    }

提交回复
热议问题