How can I transform my Factor code into Prime and Composite Identifier?

73 Views Asked by At

I already created a program that giving the factors of each inputted number.

I was in confusion of how could I get a Prime and Composite;

Problem: Accept a number and display the message "PRIME" if the number is a prime, otherwise display the message "COMPOSITE".

Well what I've said is that I created the factor code. I can't catch up what's the logic here, I know that the probable logic is in the factor code that I've created. I now want the specific answer. I want to know the logic of how could I get if its prime or composite

This is my factoring code:

import java.util.Scanner;

class factors{

    public static void main(String[] args){
        Scanner n = new Scanner(System.in);
        int num;
        int ctr=1;
        System.out.print("Enter a number : ");
        num = n.nextInt();
        while(ctr<=num){
            if(num%ctr==0){
                System.out.print(ctr + "\t");
            }
            ctr++;
        }
        System.out.println();
    }

}
1

There are 1 best solutions below

1
On

Try something like:

 boolean primeNum = true;     

 for(int ctr=2; ctr<=num/2; ctr++) {
      if (num%ctr == 0) {
          primeNum = false;
          break;
      }
 }

 if (primeNum) {
     System.out.println("Yes its a prime number");
 }

It checks the remainder after dividing the number(i.e. num%ctr). If it's perfectly divisible then remainder will be 0 and that is what i have in if condition. If condition satisfies, we break for loop and check the primeNum boolean variable for asserting the same.