nisha
nisha

Reputation: 87

Given a number n, return true is all the factors of n are prime numbers. Note that 1 and the number itself are not considered as factors

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

Upvotes: 1

Views: 204

Answers (1)

Jishnu Prathap
Jishnu Prathap

Reputation: 2043

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.

Upvotes: 1

Related Questions