Interview Questions

How to find factors of a given number ?

The following code is used to find factors of a given number in an efficient way.

public static void findFactors(int b)
{
        System.out.println("The factors for "+b+" are ");
               
        int prev = 0;
        for(int i=1;i<=b/2;i++)
        {
                if(b%i==0)
                {
                        if(prev==i )
                                return;
                        else if(i==(b/i)){
                                System.out.println(i);
                        return;
                }
               
                System.out.println(i+","+(b/i));
                       
                prev = b/i;
        }
}

Output:

The factors for 100 are
1,100
2,50
4,25
5,20
10

The factors for 35 are
1,35
5,7


The factors for 36 are
1,36
2,18
3,12
4,9
6

Note that perfect squares will have odd number of factors.