Write a Java program Factorizer.java that accepts a positive integer number as a
ID: 3670838 • Letter: W
Question
Write a Java program Factorizer.java that accepts a positive integer number as a command line argument (parse to an int n) and computes and prints out its prime factors, including multiplicities. For example, if the user enters the number 144, the program should print out:
The number n=144 has prime factors 2^4 * 3^2 because 144 = 2*2*2*2*3*3.
There are many algorithms to factorize an arbitrary integer n, but here is a simple one:
Start: Compute the list of primes not larger than sqrt(n) using your method from Exercise 15, and start from the smallest prime in the list, which will always be 2. Assign that prime to an int variable p.
1. Test to see if n is divisible by p - it is divisible if n mod p = 0. If n is divisible by p, then divide n by p and test to see if what is left over (call it n) is still divisible by p. If it is, again divide by p. Continue dividing n by p until it no longer divides by p.
Note 1: n is reduced in magnitude by a factor of p every time it’s divided by p
Note 2: Each time you find a new prime divisor, you need to store that prime factor and the total number of times that it divides n. I suggest making a list for the primes and a second list for the number of times it divides n, which is called the multiplicity of p as a prime factor. I would use an array or ArrayList. I suggest naming these lists primes and multiplicities (or mults), respectively
2. If n is a prime (you can search your prime list to see if it is – again, I strongly suggest you write a separate method to do this) or you’ve reached the end of your primes list, you're finished - so exit the loop.
3. Get the next largest prime in your list, assign it to p, and go back to start of loop.
End: Once you exit the loop, your lists of primes and multiplicities is complete.(which are the powers you need to display).Simply display the list of primes and multiplicities in the format given above. For example, for n = 144, primes and multiplicities arrays should look like:
primes[]: [2, 3] multiplicities[]: [4, 2]
Or, for another example, the number 19404 factors to 2^2 * 3^2 * 7^2 * 11^1, so primes and multiplicities arrays should look like:
primes[]: [2, 3, 7, 11] multiplicities[]: [2, 2, 2, 1]
Explanation / Answer
public class prime_Factors { public static void main(String[] args) { // command-line argument long number = Long.parseLong(args[0]); System.out.print("The prime factors of the numbers are " + number + " is: "); // here we will find each potential factor i for (long i = 2; i*i 1 if (number > 1) System.out.println(number); else System.out.println(); } }Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.