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

Find factors of a number

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

Problem

I am a beginner in C. I have just written this program to find the factors of a provided number \$n\$ where \$1\leq n \leq 10^9\$. However, when I input large numbers (e.g. the maximum, \$10^9\$), the program takes a long time to finish finding the larger factors. How do I reduce its time taken? Also, are there any possible improvements for this code?

#include
int main(){
    int a,i;
    scanf("%d",&a);
    for(i=1;i<(a/2+1);i++){
        if(a%i==0){
            printf("%d\n",i);
        }
    }
    printf("%d\n",a);
    return 0;
}

Solution

You should realize that if \$i\$ is a divisor of \$a\$, then so is \$a / i\$. This way you get two divisors per found divisor.

In the same vein, you only need to search up to \$\sqrt{n}\$, because all factors above that have already been found as the second divisor.

So your code would become:

#include 
#include 

int main(){
        int a,i;
        scanf("%d",&a);
        int bound = ceil(sqrt(a));
        for(i=1; i <= bound; i++) {
                if(a%i==0) {
                        printf("%d\n",i);
                        if(a/i != i) printf("%d\n", a/i);
                }
        }
        printf("%d\n",a);
        return 0;
}

Code Snippets

#include <stdio.h>
#include <math.h>

int main(){
        int a,i;
        scanf("%d",&a);
        int bound = ceil(sqrt(a));
        for(i=1; i <= bound; i++) {
                if(a%i==0) {
                        printf("%d\n",i);
                        if(a/i != i) printf("%d\n", a/i);
                }
        }
        printf("%d\n",a);
        return 0;
}

Context

StackExchange Code Review Q#163462, answer score: 3

Revisions (0)

No revisions yet.