1
public class AllFactorsArePrime {

public static void main(String[] args) {
    AllFactorsArePrime obj = new AllFactorsArePrime();
    boolean result = obj.areAllFactorsPrime(8);
    System.out.println(result);
}

public boolean areAllFactorsPrime(int n) {

        int j=0;
        double k=n;
        while(n%2==0){
        n=n/2;
        j=2;
        }

        for(int i=3; i<=n;i=i+2){
        while(n%i==0){
        n=n/i;
        j=i;
        }
        }

        if(j==0 ){
        return 1;
         }
        return j;
        }

above code return prime factors, but return should be true or false.any suggestion? Sample Input #1

areAllFactorsPrime(22)

Sample Output #1

true 

Sample Input #2

areAllFactorsPrime(25)

Sample Output #2

true

Sample Input #3

areAllFactorsPrime(32)

Sample Output #3

false
Blake Yarbrough
  • 2,286
  • 1
  • 20
  • 36
nisha
  • 87
  • 6
  • 1
    Every number has a prime factorization, all the factors of the number will be the primes from that factorization and all their products. It seems that the only case in which all the factors will be prime is when a number is a square of a prime. – Danil Gaponov Jul 30 '15 at 13:40
  • 1
    Please clear my doubt , 5 and 7 are prime number but 5*7 = 35 (factors of 35 is 1,5,7,35) so it has all prime factors except 1 and 35. So square of prime number is not the only case. – rhitz Jul 30 '15 at 13:56

1 Answers1

1

I think this is what you are trying to achieve!

import java.util.*;
import java.lang.*;
import java.io.*;

public class AllFactorsArePrime {
    public static void main(String[] args) {
        AllFactorsArePrime obj = new AllFactorsArePrime();
        boolean result = obj.areAllFactorsPrime(32);
        System.out.println(result);
    }

    public boolean areAllFactorsPrime(int n) {
            int count=0;
            int j=0;
            double k=n;
            while(n%2==0){
            n=n/2;
            j=2;
            count++;
            }

            for(int i=3; i<=n;i=i+2){
            while(n%i==0){
            n=n/i;
            j=i;
            count++;
            }
            }

           if(count>=3)
           {
               return false;
           }
           else
               return true;
            }
}

The logic is pretty simple if you have more than 2 prime factors excluding 1 , that means you have atleast 1 composite factor which is prime1*prime2.

Jishnu Prathap
  • 1,955
  • 2
  • 21
  • 37