Computer Science, asked by mrudraprasad60, 6 months ago

Write a program to accept a number and print only prime factors.​

Answers

Answered by arjunsecond00
0

Explanation:

Efficient program to print all prime factors of a given number

While n is divisible by 2, print 2 and divide n by 2.

After step 1, n must be odd. Now start a loop from i = 3 to square root of n. While i divides n, print i and divide n by i. ...

If n is a prime number and is greater than 2, then n will not become 1 by above two steps. So print n if it is greater than 2.

Answered by Oreki
3

import java.util.Scanner;

public class PrimeFactors {

   static void primeFactors(int number) {

       System.out.print("Prime factors - ");

       

       for (; number % 2 == 0; number /= 2)

           System.out.print(2 + " ");

       

       for (int i = 3; i <= Math.sqrt(number); i+= 2)

           for (; number % i == 0; number /= i)

               System.out.print(i + " ");

       

       System.out.println((number > 2) ? number : "");  

   }  

   

  public static void main(String[ ] args) {

       System.out.print("Enter a number - ");

       primeFactors(new Scanner(System.in).nextInt( ));

   }

}

Similar questions