Factors of a numbers

Brute force solution:

public class factors{
public static void main(String[] args) {
int n = 20;
findFactors(n);
}
static void findFactors(int n){
for(int i = 1; i <= n; i++){
if(n%i == 0){
System.out.print(i + " ");
}
}
}
}

Somewhat optimized:

public class factors{
public static void main(String[] args) {
int n = 20;
findFactors(n);
}
static void findFactors(int n){
for(int i = 1; i <= n/2; i++){
if(n%i == 0){
System.out.print(i + " ");
}
}
System.out.print(n + " ");
}
}

Optimized solution:

public class factors{
public static void main(String[] args) {
int n = 36;
findFactors(n);
}
static void findFactors(int n){
//create a list to store the 2nd half factors
ArrayList<Integer> list = new ArrayList<>();

//run the loop root of n times
for(int i = 1; i*i <= n; i++){
if(n%i == 0){

//if n/i == i it means that it is the root of n so, to avoid repetition of
//root print it just 1 time
if(n/i == i){
System.out.print(i + " ");
}
else{
System.out.print(i + " ");
list.add(n/i);
}
}
}
//print the second half of factors
for(int i = list.size()-1; i >= 0; i--){
System.out.print(list.get(i) + " ");
}

}
}

--

--

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Palakkgoyal

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.