Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimizing my code for finding the factors of a given integer

Tags:

c++

factors

Here is my code,but i'lld like to optimize it.I don't like the idea of it testing all the numbers before the square root of n,considering the fact that one could be faced with finding the factors of a large number. Your answers would be of great help. Thanks in advance.

unsigned int* factor(unsigned int n)
{    
    unsigned int tab[40];
    int dim=0;
    for(int i=2;i<=(int)sqrt(n);++i)
    {
        while(n%i==0)
        {
            tab[dim++]=i;
            n/=i;
        }
    }
    if(n>1)
        tab[dim++]=n;
    return tab;
}
like image 818
Victor Chima Avatar asked Dec 09 '22 20:12

Victor Chima


2 Answers

Here's a suggestion on how to do this in 'proper' c++ (since you tagged as c++).

PS. Almost forgot to mention: I optimized the call to sqrt away :)

See it live on http://liveworkspace.org/code/6e2fcc2f7956fafbf637b54be2db014a

#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>

typedef unsigned int uint;

std::vector<uint> factor(uint n)
{    
    std::vector<uint> tab;

    int dim=0;
    for(unsigned long i=2;i*i <= n; ++i)
    {
        while(n%i==0)
        {
            tab.push_back(i);
            n/=i;
        }
    }
    if(n>1)
        tab.push_back(n);
    return tab;
}

void test(uint x)
{
    auto v = factor(x);
    std::cout << x << ":\t";
    std::copy(v.begin(), v.end(), std::ostream_iterator<uint>(std::cout, ";"));
    std::cout << std::endl;
}

int main(int argc, const char *argv[])
{
    test(1);
    test(2);
    test(4);
    test(43);
    test(47);
    test(9997);
}

Output

1:  
2:  2;
4:  2;2;
43: 43;
47: 47;
9997:   13;769;
like image 88
sehe Avatar answered Mar 15 '23 16:03

sehe


There's a simple change that will cut the run time somewhat: factor out all the 2's, then only check odd numbers.

like image 20
Pete Becker Avatar answered Mar 15 '23 16:03

Pete Becker