87.7k views
2 votes
Design an algorithm for finding all the factors of a positive integer. For example, in the case of the integer 12, your algorithm should report the values 1, 2, 3, 4, 6, and 12

User Tuzzer
by
9.7k points

1 Answer

4 votes
As I say to every one requesting programming help on these forums. If you don't specify a language, then it just means you'll have to translate the answer that is given to you, to a different language. Here's what you want in Java:


import java.util.InputMismatchException;
import java.util.Scanner;

public class Test {
public static void main(String[] args) {
int number = numInput();
printFactors(Math.abs(number));
}

private static int numInput() {
Scanner sc = new Scanner(System.in);

System.out.print("Enter number: ");

int input;
while (true) {
try {
input = sc.nextInt();
break;
} catch (InputMismatchException e) {
System.out.println("Not a number.");
}
}

return input;
}

private static void printFactors(int number) {
if (number == 0) {
System.out.println("Infinite factors.");
} else {
for (int i = 1; i <= number; i++) {
for (int j = 1; j <= number; j++) {
if (i * j == number) {
System.out.print(i + ", ");
}
}
}
}
}
}
User Humungs
by
8.4k points