How to identify the input value if it is a prime or a composite number?

5.8k Views Asked by At

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

I cant sleep to think how could i write a code for this. I was thinking that it could be easy if i get the logic here. Sorry guys, Im just a beginner

So could you help me how to solve this problem.

My professor told me that i can get the logic in these code, but I'm still confuse :D

here's my last code for getting the factor that my prof told me that i could get the logic here. (i dont know how :D)

import java.util.Scanner;
public 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();
  }
}

}

2

There are 2 best solutions below

1
On

Well, this is a little vague as to what you should be doing.

The way this is done in practice is with a probabilistic algorithm like Rabin-Miller, which can be set to give the right answer with whatever degree of accuracy you like, and is far, far more efficient than a deterministic algorithm that guarantees to give the right answer.

If you want to write a deterministic algorithm, though, you can determine whether n is prime by trying all possible factors from 2 up to sqrt(n), and seeing if any of them divides exactly into n. Your code goes right up to n, which is inefficient. It will also decide that all values are composite, because n always goes exactly into n. At the very least, you should stop at n-1. You also need to start at 2 rather than 1, because 1 always goes exactly into n.

0
On

You should make this by yourself, but anywa here you have quite not optimal code for this:

Scanner n = new Scanner(System.in);

    int num;
    int ctr=2;
    boolean prime = true;

    System.out.print("Enter a number : ");
    num = n.nextInt();

    while(ctr<num){

        if(num%ctr==0){

            prime = false


    break;
}
        ctr++;
    }

    if (prime) {
        System.out.println("PRIME");
    } else {
        System.out.println("COMPOSITE");
    }