Find all Factors of Integer

Factors are the numbers that can divide any given integer completely. The simplest way to solve this problem is to divide every number from 1 to a given integer, or There are certain observations regarding factors.

  • 1 and the digit itself will always be the factor.
  • Factors always come in pairs, for example, if we take 60 then its factors are 1*60, 2*30, 3*20, etc
  • The largest factor of any digit is the digit itself.
  • 2nd largest factor will be N/2, the 3rd largest factor is N/3 and the 4th largest factor is N/4, and so on.
  • Factors will always be less than the square root of the number.
package org.wesome.dsalgo;

import java.util.ArrayList;
import java.util.List;

public class FindFactors {
    public static List<Integer> findFactors(int number) {
        List<Integer> factors = new ArrayList<>();
        int squrRootOfN = (int) Math.sqrt(number);
        int i;
        for (i = 1; i < squrRootOfN; i++) {
            if (number % i == 0) {
                System.out.println(i + " and " + number / i + " is a factor");
                factors.add(i);
                factors.add(number / i);
            }
        }
//         if number is a perfect square
        if (number % i == 0) {
            System.out.println(i + " is a factor");
            factors.add(i);
        }
        System.out.println("factors = " + factors);
        return factors;
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.List;

public class FindFactorsTest {
    @Test
    void findFactorsTest1() {
        List<Integer> factors = Arrays.asList(new Integer[]{1, 16, 2, 8, 4});
        Assertions.assertTrue(factors.equals(FindFactors.findFactors(16)));
    }

    @Test
    void findFactorsTest2() {
        List<Integer> factors = Arrays.asList(new Integer[]{1, 100, 2, 50, 4, 25, 5, 20, 10});
        Assertions.assertTrue(factors.equals(FindFactors.findFactors(100)));
    }

    @Test
    void findFactorsTest3() {
        List<Integer> factors = Arrays.asList(new Integer[]{1, 16, 2, 8, 4});
        Assertions.assertTrue(factors.equals(FindFactors.findFactors(16)));
    }
}
plugins {
    id 'java'
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}

follow us on