HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Simplifying and optimizing factors and prime factorization generator

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
factorsgeneratoroptimizingsimplifyingandprimefactorization

Problem

My first algorithm for finding the factors of a number was pretty slow and horrible (it started at \$O(n^2)\$, where n was not even the inputted number), but I eventually came up with this new code. I just want the first factors of a number (not the duplicates), so I used sqrt(n) instead of n for the loop. As for the prime factorization, it appears to be efficient but it could probably be improved.

  • Could this program be written simpler and more efficiently?



  • Are all of these std::stringstreams even necessary?



  • Is there a better way of having findPrimeFactorization() output in the form of w^x * y^z?



#include 
#include 
#include 
#include 
#include 

using std::cin;
using std::cout;
using std::vector;
using std::string;
using std::stringstream;

string findFactors(unsigned, vector &factors);
string findPrimeFactorization(unsigned posInt);

int main()
{
    unsigned positiveInteger;

    cout  Pos. Integer: ";
    cin >> positiveInteger;

    vector factors;

    cout  &factors)
{
    std::stringstream factorsStr;
    double sqrtInt = sqrt(static_cast(posInt));

    for (unsigned i = 1; i = 1)
        {
            primesStr  1)
                primesStr << '^' << powerDegree;
            if (i <= posInt)
                primesStr << " x ";
        }
    }

    return primesStr.str();
}

Solution

I have a couple of suggestions that you may wish to consider:

-
Don't return a string with the complete statement, return a std::vector/std::map instead with the values, and later assemble the string. It will keep the values in a more usable form and separate out the concerns. You're half doing this with findFactors, go all the way!

-
In findPrimeFactorization, your main loop has a terminating condition that varies both sides (i

-
In
findPrimeFactorization, to speed things up (slightly) you can try testing 2 separately, then 3, 5, 7... within the loop (other more complex shortcuts are available)

-
In terms of writing out the prime factors, you can combine the ideas behind the questions infix_iterator code and
std::copy to std::cout for std::pair` to get something that's nice, if a little obscure.

Context

StackExchange Code Review Q#24399, answer score: 6

Revisions (0)

No revisions yet.