Question

I have a piece of code to compute the factors of a number. These factors are then used to program two dimensions of a controller (m * N). The controller generates an interrupt every N bytes so it is beneficial to choose the largest N possible within the controllers limitation. In the code fragment below I call this limit MAX_DIM.

The code listed below is functional and calculates the factors as described above. My question is about a corner case that I'm currently not handling in an optimal way.

Although it is unlikely, the function will need to handle an input value that is prime and larger than MAX_DIM; and in this case it should return an error. In the code fragment below I handle this by checking one of the factors (m) until it reaches an arbitrarily selected value, at which point I determine that finding a factor is no longer feasible. Although this works in practice I'm almost certain there has to be mathematically and computationally more elegant way to detect this case. Looking for some pointers to algorithms I can adapt for this situation.

m = tr_size/MAX_DIM;  // sets up a minimum value for m


if (m == 0)
{
    N = tr_size;
    m = 1;
    return 0;
} 
else
{
    /* TODO: check for m <= 128 ensures a mechanism to quit if 
     * tr_size is a prime number. Is there a better way to do this?
     */

    while ((((tr_size/m) > MAX_DIM) || (tr_size % m) != 0) && (m <=128))
    {
        m++;        
    }

    if (m > 128) 
    {
        return 1;  // error: cannot compute factors

    }

    N = tr_size/m;

    return 0;
}
Was it helpful?

Solution

When checking for factors you only have to check values less than or equal to the square root of the number being factored. Any factor larger than the square root will have a corresponding factor less than the square root.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top