It is a well-known mathematical fact that every integer greater than or equal to
ID: 3677366 • Letter: I
Question
It is a well-known mathematical fact that every integer greater than or equal to 2 has a unique factorization into prime numbers. For example:
40 = 2 * 2 * 2 * 5
58 = 2 * 29
9 = 3 * 3
30 = 2 * 3 * 5
100 = 2 * 2 * 5 * 5
Write a recursive function:
void printPrimeFactorization(int n, bool firstcall);
that prints out the prime factorization of the number n. (You will need to figure out for yourself the purpose of the boolean argument firstcall.)
For example, if n == 40, it should print out:
The prime factorization of 40 is 2 * 2 * 2 * 5.
also, our professor ask us to write a loop to find the smallest integer greater than or equal to 2 that divides n,
then print out this integer and call the function recursively on n/k
Explanation / Answer
PrimeFactors.java
package org.students;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
class PrimeFactors {
public static void main(String args[]) {
int n=0,k=0;
while (true) {
ArrayList<Integer> al = new ArrayList();
System.out.print("Enter a Number : ");
Scanner sc = new Scanner(System.in);
n= sc.nextInt();
k=n;
System.out.print("The Prime Factors of " + n + " are : ");
int i = 2;
while (n > 1) {
if (n % i == 0) {
System.out.print(i + " ");
n = n / i;
al.add(i);
} // end of if
else
i++;
}// end of while
int fmin = al.get(0);
for (Integer x : al) {
if (x < fmin) {
fmin = x;
}
}
System.out.println(" ");
System.out.println("Smallest Prime Integer that divides "+k+" is :"+ fmin);
System.out.print(" Do You want to continue(Y/N):");
char c = sc.next(".").charAt(0);
if (c == 'Y' || c == 'y') {
continue;
}
System.out.println("* Program Exit *");
break;
}// end of while(true)
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.