Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create a java program which prompts the user for a number. The program then calc

ID: 3688219 • Letter: C

Question

Create a java program which prompts the user for a number. The program then calculates the prime factors of that number USING RECURSION. If you don't use recursion in your program, you will not get credit.


Your program should then output the prime factors in sorted order.

For example, the prime factors for 6 are 2x3.   

For 12, 2 is a prime factor, leaving 6 (2x6=12). So, you could then determine the prime factors of 6, resulting in 2 and 3 as the prime factors. Thus, the factors are 2, 2, 3. This example also gives you a hint regarding a recursive algorithm.

To better understand prime factors, check out: http://www.mathsisfun.com/prime-factorization.html

Please make sure you comment your code thoroughly.

The code should be nicely formatted and should use proper variables.

Explanation / Answer

PrimeFactor.java


public class PrimeFactor {

   /**
   * @param args
   */
   public static void main(String[] args) {
       // TODO Auto-generated method stub
       java.util.Scanner in = new java.util.Scanner(System.in);
       System.out.println("Please Enter a number :");
       int inputNUmber = in.nextInt();
       primeFactors(inputNUmber);

   }
   /*Method is used to find the prime factors*/
   public static void primeFactors(int n) {
   if (isPrime(n))
   {
   System.out.print(n+" ");
   return;
   }

   int i = 2;
   while (i < n/2)
   {
   if (n % i == 0)
   {
   if (isPrime(i))
   {
   System.out.print(i + " ");
   /*Recursive method call*/
   primeFactors(n/i);
   return;
   }
   }
   i++;
   }
   return;
   }
   /*method is used to verify whether the number is prime or not*/
   public static boolean isPrime( int n )
   {
   int i;

   if( n < 2 )
   return false;
   else
   {
   for( i = 2; i < n; i += 1 )
   {
   if( n % i == 0 )
   return false;
   }
   }

   return true;
   }

}

Output:

Please Enter a number :
48
2 2 2 2 3

Please Enter a number :
147
3 7 7

Please Enter a number :
17
17

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote