Find the Most Factors – Solution

The challenge for this month’s Exercise is to discover those values in the range 1 to 999 that have the highest number of factors. Never mind the math! Let C and the computer do the work for you.

I devised a solution in three parts:

First, determine the factors of values from 1 through 999. This loop was borrowed from my earlier prime number example. The big difference is that the factors for each value is stored in an array, factors[]:

factors[v]++;

Variable v represents the value examined, which is tied to an element in the factors[] array. This approach makes sense when you study the earlier code example.

Second, I find the maximum (largest) value in the factors[] array. This part of the code uses a find-the-maximum-value algorithm. Further, I’m interested only in the value, not the element number. The value is saved in variable max.

Third and finally, a loop plows through all elements in the factors[] array to see which match the max value. This way, should multiple values have the same number of factors, all are output.

Here’s my solution:

2020_01-Exercise.c

#include <stdio.h>

#define SIZE 1000

int main()
{
    int factors[SIZE];
    int v,x,max;

    /* determine the factors */
    v = 1;
    while(v<SIZE)
    {
        factors[v] = 1;
        for( x=1; x<v; x++ )
        {
            if( v%x == 0 )
            {
                factors[v]++;
            }
        }
        v++;
    }

    /* obtain the greatest factor */
    max = 0;
    for( x=1; x<SIZE; x++ )
    {
        if( factors[x]>max )
            max = factors[x];
    }

    /* Show the highest factors */
    /* This also accounts for multiple values */
    for( x=1; x<SIZE; x++ )
    {
        if( factors[x]==max )
            printf("%d has %d factors\n",x,max);
    }

    return(0);
}

The highest number of factors is determined by running the code. The winner is:

840 has 32 factors

Impressive — and not what I expected, but it checks out. I figured multiple values would have a high number of factors, but the winner is 840.

The code can be improved upon, naturally. If I knew maths better than I do, I’m sure some algorithms or rules exist for eliminating some numbers as impossible factors. Pulling them out of the factor loop could optimize the code. Other approaches exist to solve the problem, which is true of all programming.

If your solution worked and yielded the same result, great! I find programming exercises fun not only to work out a problem (and the solution may come in handy later), but also to discover the multiple ways that a single task can be implemented.

Leave a Reply