Program is to calculate the prime factorization, the prime factorization theorem
ID: 3581446 • Letter: P
Question
Program is to calculate the prime factorization, the prime factorization theorem states that every positive integer is uniquely factorable into a product of prime numbers. The below code is set to calculate only for the number 40. Please alter code to ask the user to enter a number, then take that number and calculate the prime factorization.
import java.util.*;
public class PrimeFactorization {
public static void main(String[] args) {
ArrayList<Integer> factors = new ArrayList<>();
// adding 1 in list
factors.add(1);
int s = 2;
int num = 40;
int n = num;
// loop till divisors is less than dividend
while (s <= n) {
// divide n by s till it is divisible
while (n != 1 && n % s == 0) {
factors.add(s);
n = n / s;
}
s = s + 1;
}
factors.add(num); // adding number itself in list
System.out.println(factors);
// finding factors
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
System.out.print(i + " ");
}
}
System.out.println();
}
}
Explanation / Answer
import java.util.*;
public class PrimeFactorization {
public static void main(String[] args) {
ArrayList<Integer> factors = new ArrayList<>();
// adding 1 in list
factors.add(1);
int s = 2;
System.out.print("Enter a positive interger:");
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
int n = num;
// loop till divisors is less than dividend
while (s <= n) {
// divide n by s till it is divisible
while (n != 1 && n % s == 0) {
factors.add(s);
n = n / s;
}
s = s + 1;
}
factors.add(num); // adding number itself in list
//System.out.println(factors);
// finding factors
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
System.out.print(i + " ");
}
}
System.out.println();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.