Почему моя программа не определяет простые числа?

0

Я использую метод Sieve of Erastosthenes, чтобы сделать программу, которая печатает все простые числа до 1000. Программа работает, но по какой-то причине программа не удалит числа, которые являются составными. Поскольку моя программа работает, я уверен, что это всего лишь логическая ошибка и что ошибка находится где-то в моей функции identPrimes, но я не смог ее найти.

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

void initializeNumbers ( char number[], int ARRAY_SIZE )
{
    number[0]  =  'I' ; // 'I' means Ignore
    number[1]  =  'I' ;

    for ( int i = 2 ; i < ARRAY_SIZE ; i ++ )
        number[i]  =  'U' ;

    /*  --------------------------------------------------------
        Function indexOfLeastU returns the least index such that
        the character stored at that index is 'U', with the
        exception that -1 is returned if no array element has
        value 'U'.
        -------------------------------------------------------- */
    int indexOfLeastU ( char number[], int ARRAY_SIZE )
    {
        for ( int i = 0 ; i < ARRAY_SIZE ; i ++ )
            if ( number[i] == 'U' )
                return  i ;

        return  -1 ;
    } // end indexOfLeastU function

    /*  --------------------------------------------------------
        Function identifyPrimes identifies which numbers are
        prime by placing 'P at those indices.
        Composite # are marked with 'C's.
        -------------------------------------------------------- */
    void  identifyPrimes ( char number[], int ARRAY_SIZE )
    {
        int  leastU  =  indexOfLeastU ( number, ARRAY_SIZE ) ;
        while ( leastU >= 0 )
            {
                number [leastU]  =  'P' ; // 'P' for Prime

                // mark multiples as Composite ...
                for ( int i = (2 * leastU) ; i < ARRAY_SIZE ; i += leastU)

                    number [leastU]  =  'C' ; // 'C' for Composite
                leastU  =  indexOfLeastU ( number, ARRAY_SIZE ) ;

            } // end while loop
    } // end identifyPrimes function

    /*  --------------------------------------------------------
        Function printPrimes prints those array indices whose
        corresponding elements have the value 'P'.
        -------------------------------------------------------- */
    void printPrimes ( char number[], int ARRAY_SIZE )
    {
        // print the indices at which a 'P' is stored ...
        cout << "\nThe prime numbers up to 1000 are:\n\n" ;
        for ( int i = 0 ; i < ARRAY_SIZE ; i ++ )
            if ( number[i] == 'P' )
                cout << i << '\t' ;
        cout << endl << endl ;
    } // end printPrimes function

    int main ( )
    {
        // declare & initialize constants ...
        const int  MAX_NUMBER  =  1000 ;
        const int  ARRAY_SIZE  =  MAX_NUMBER + 1 ;

        // declare array ...
        char  number [ ARRAY_SIZE ]  =  { '\0' } ;

        initializeNumbers ( number, ARRAY_SIZE ) ;

        identifyPrimes ( number, ARRAY_SIZE ) ;

        printPrimes ( number, ARRAY_SIZE ) ;
        system("pause");
    } // end main function
  • 1
    Ваши фигурные скобки не сбалансированы, закрытие функции initializeNumbers() .
  • 0
    Вы должны иметь привычку всегда помещать {...} вокруг тел if , while , for и т. Д., Даже если в теле есть только одно утверждение.
Показать ещё 4 комментария
Теги:
arrays

3 ответа

3
Лучший ответ

Проблема здесь:

    // mark multiples as Composite ...
    for ( int i = (2 * leastU) ; i < ARRAY_SIZE ; i += leastU)

        number [leastU]  =  'C' ; // 'C' for Composite

Назначение должно быть:

        number[i] = 'C';
2

Здесь есть проблема.

for ( int i = (2 * leastU) ; i < ARRAY_SIZE ; i += leastU)
    number [leastU]  =  'C'

Должен быть

number[i] = 'C';
1

Во-первых, вместо знака ignor вы должны реализовать это со связанным списком (вы можете использовать std :: list). то вы можете просто удалить те элементы, которые вы сейчас указываете, чтобы их игнорировать.

Эта программа (по крайней мере, как показано здесь) не будет компилироваться, поскольку вы забыли закрывать скобки для initializeNumbers.

Затем вам нужно исправить этот цикл:

for ( int i = (2 * leastU) ; i < ARRAY_SIZE ; i += leastU)

                number [leastU]  =  'C' ; // 'C' for Composite

Вам нужно использовать i вместо leastU

Ещё вопросы

Сообщество Overcoder
Наверх
Меню