Created
October 25, 2021 01:14
-
-
Save kabinpokhrel/48b0f6dca716633199204bb97d72cef4 to your computer and use it in GitHub Desktop.
Checking if the provided number is prime, composite or 0,1 and -1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class PrimeComposite { | |
// calculate the remainder of the given number | |
public static int reminder(int numb, int divisor) { | |
return Math.floorMod(numb, divisor); | |
} | |
public static void main(String[] args) { | |
System.out.print("Enter a number: "); | |
Scanner sc = new Scanner(System.in); | |
// taking an input of number as n | |
int n = sc.nextInt(); | |
// Checking if numbers are 0,1 or -1 | |
if (n == 0 || n == 1 || n == -1) { | |
System.out.println("\"n\" = 0,1,-1"); | |
} else { | |
boolean test = true; | |
int i = 2; | |
// checking if either the absolute square root of the given number is equal or less than the number 2 | |
// i.e. the prime case in first run, | |
// and then following the next execution being absolute given number not being prime | |
while (i<= Math.sqrt(Math.abs(n))){ | |
if (reminder(n, i) == 0){ | |
test = false; | |
i = Math.abs(n); | |
} | |
i++; | |
} | |
// if the test is right, | |
if (test){ | |
System.out.println("n is prime!"); | |
}else{ | |
System.out.println("n is composite!"); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment