What be up?

This is a discussion on What be up? within the C++ Programming forums, part of the General Programming Boards category; Okay I have sat down and am now really confused as why this program is not working. It's supposed to ...

  1. #1
    Registered User cyberCLoWn's Avatar
    Join Date
    Dec 2003
    Location
    South Africa
    Posts
    124

    What be up?

    Okay I have sat down and am now really confused as why this program is not working. It's supposed to start at array subscript 2 and evertime an array element if found whose value is 1, then loop throuh the remainder of the array and set to zero every element whose subscript is a multiple of the subscript for the element with value 1. For array subscript 2, all emelents beyond 2 in the array that are multiples of 2 will be set to zero (subscripts 4, 6, 8, 10, etc).

    Code:
    // The Seive of Eratosthenes
    
    #include <iostream>
    using std::cout;
    using std::cin;
    
    // Prototypes
    
    
    int main()
    {
       const int arraySize = 30;
       int array[ arraySize ] = { 0 };
       
       for( int i = 2; i < arraySize; i++ )
    
          for( int j = 0; j < arraySize; j++ )
             if( array[ j ] == 0 )
                if( j % i )
                   array[ j ] = 1;
               
       cout << "Prime numbers are: ";
       
       // output subscripts of array whose value = 1
       for( int i = 0; i < arraySize; i++ )
          if( array[ i ] == 0 )
             cout << i << ' ';
    
       cin.get();
       return 0;
    }

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    Compare and contrast.
    Code:
    // The Seive of Eratosthenes
    #include <iostream>
    using std::cout;
    using std::cin;
    
    int main()
    {
      const int arraySize = 30;
      int array[ arraySize ] = { 0 };
    
      for( int i = 2; i < arraySize; i++ ) {
        if( array[ i ] == 0 ) {
          for( int j = i; i * j < arraySize; j++ )
            array[ i * j ] = 1;
        }
      }
      cout << "Prime numbers are: ";
      for( int i = 2; i < arraySize; i++ ) {
        if( array[ i ] == 0 )
          cout << i << ' ';
      }
      cin.get();
    
      return 0;
    }
    My best code is written with the delete key.

  3. #3
    Registered User cyberCLoWn's Avatar
    Join Date
    Dec 2003
    Location
    South Africa
    Posts
    124
    I saw what I did wrong. Thanks Prelude. Much appreciated dude.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21