Prime numbers program

后端 未结 14 1643
无人及你
无人及你 2021-01-07 00:27

I\'m currently trying out some questions just to practice my programming skills. ( Not taking it in school or anything yet, self taught ) I came across this problem which re

14条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-07 00:50

    I'm trying to improve my functional programming at the moment so I just coded up the sieve quickly. I figure I'll post it here. If you're still learning, you might find it interesting, too.

    #include 
    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    class is_multiple : public binary_function
    {
        public:
            bool operator()(int value, int test) const
            {
                if(value == test) // do not remove the first value
                    return false;
                else
                    return (value % test) == 0;
            }
    };
    
    int main() 
    {
        list numbersToTest;
        int input = 500;
    
        // add all numbers to list
        for(int x = 1; x < input; x++)
            numbersToTest.push_back(x);
    
        // starting at 2 go through the list and remove all multiples until you reach the squareroot
        // of the last element in the list
        for(list::iterator itr = ++numbersToTest.begin(); *itr < sqrt((float) input); itr++)
        {
            int tmp = *itr;
            numbersToTest.remove_if(bind2nd(is_multiple(), *itr));  
            itr = find(numbersToTest.begin(), numbersToTest.end(), tmp); //remove_if invalidates iterator 
                                                                     // so find it again. kind of ugly
        }
    
        // output primes
        for(list::iterator itr = numbersToTest.begin(); itr != --numbersToTest.end(); itr++)
            cout << *itr << "\t";
    
        system("PAUSE");
    
        return 0;
    }
    

    Any advice on how to improve this would be welcome by the way.

提交回复
热议问题