All Factors

Given a number N, find all factors of N.

Example:

N = 6 
factors = {1, 2, 3, 6}

Make sure the returned array is sorted.

public class Solution {
    public int[] allFactors(int x) {
        ArrayList<Integer> arr = new ArrayList<>();
        for(int i =1;i*i<=x;i++) {
            if(x%i==0) {
                arr.add(i);
                if(i*i != x)
                    arr.add(x/i);
            }
        }
        int ans[]= new int[arr.size()];
        for(int i =0;i<ans.length;i++)
            ans[i]= arr.get(i);
        Arrays.sort(ans);
        return ans;
    }
}

Last updated