Unusual Speed Difference between Python and C++

后端 未结 17 2299
庸人自扰
庸人自扰 2020-12-22 21:25

I recently wrote a short algorithm to calculate happy numbers in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it.

17条回答
  •  一个人的身影
    2020-12-22 21:51

    Well, I also gave it a once-over. I didn't test or even compile, though.

    General rules for numerical programs:

    • Never process numbers as text. That's what makes lesser languages than Python slow, so if you do it in C, the program will be slower than Python.

    • Don't use data structures if you can avoid them. You were building an array just to add the numbers up. Better keep a running total.

    • Keep a copy of the STL reference open so you can use it rather than writing your own functions.


    void calcMain(int upperBound)
    {
        vector known;
        for(int i = 0; i <= upperBound; i++)
        {
            int current = i;
            vector history;
            do
            {
                squaresum = 0
                for ( ; current; current /= 10 )
                {
                    int digit = current % 10;
                    squaresum += digit * digit;
                }
                current = squaresum;
                history.push_back(current);
            } while ( ! count(history.begin(), history.end() - 1, current) );
    
            if(current == 1)
            {
                known.push_back(i);
                //cout << i << "\t";
            }
    
        }
        //cout << "\n\n";
    }
    

提交回复
热议问题