I want to write a program in Java that return a prime factorization of any natural number greater than one.
After spending some time coding and debugging, the program runs fine. Since I am new to Java and programming in general, I don't know how bad my code style and class/method design are. Hence, I am here asking for some tips/advice on what I did wrong and what I could do to improve.
public class FTA_Prime_Factorization {
/**
* A method to ask for a integer input from user.
*
* @return num: int
*/
protected static int user_input() {
int num;
Scanner inp;
while (true) {
inp = new Scanner(System.in);
System.out.print("Please enter a greater-than-1 positive integer: #");
if (inp.hasNextInt() && (num = inp.nextInt())>1)
break;
System.out.println("Please enter a integer greater than 1!!!");
}
return num;
}
/**
* To check whether the parameter is a prime number.
*
* @param x: int
* @return counts == 2: boolean
*/
private static boolean checkPrime (int x) {
int counts = 0;
for (int i = x; i > 0; i--) {
if (x % i == 0) {
counts++;
}
}
return counts == 2;
}
/**
* To create an Arraylist of prime number that is less than 10000.
*
* @return primeList: Arraylist<Integer>
*/
private static ArrayList<Integer> primes() {
ArrayList<Integer> primeList = new ArrayList<>();
for (int x = 1; x < 10000; x++){
if (checkPrime(x))
primeList.add(x);
}
return primeList;
}
/**
* To create an Arraylist of prime factorization of the parameter.
*
* @param x: int
* @return primeFactors: Arrarylist<Integer>
*/
private static ArrayList<Integer> array(int x) {
ArrayList<Integer> primeFactors = new ArrayList<>();
ArrayList<Integer> listOfPrime = primes();
for (int i : listOfPrime) {
for (int j = x; j % i== 0; j /= i)
primeFactors.add(i);
}
return primeFactors;
}
public static void main(String [] args) {
ArrayList<Integer> temp = array(user_input());
HashMap<Integer, Integer> counter = new HashMap<>();
String primeFactors = "";
for (int element : temp) {
if (counter.get(element) != null){
counter.put(element, counter.get(element)+1);
}else{
counter.put(element, 1);
}
}
System.out.print("Canonical Form Prime factorization of x = ");
for (int key : counter.keySet()) {
primeFactors += counter.get(key) == 1 ? "(prime)"+key + " x " : "(prime)"+key+"^"+counter.get(key) + " x ";
}
System.out.println(primeFactors.substring(0, primeFactors.length() - 3));
}
}
An example output (input = 3612):
Canonical Form Prime factorization of x = (prime)2^2 x (prime)3 x (prime)7 x (prime)43