FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
basic-programs/java/PrimeCheck.java at master · Skm26/basic-programs · GitHub
Skm26
/
basic-programs
Public
forked from
utkarsh-shekhar/basic-programs
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
basic-programs
/
java
/
PrimeCheck.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
43 lines (37 loc) · 1.6 KB
Breadcrumbs
basic-programs
/
java
/
PrimeCheck.java
Copy path
File metadata and controls
43 lines (37 loc) · 1.6 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import
java
.
util
.
InputMismatchException
;
import
java
.
util
.
Scanner
;
/**
* To check whether a given number is prime
*/
public
class
PrimeCheck
{
public
static
void
main
(
String
[]
args
) {
// Accept input from the console
System
.
out
.
print
(
"Please enter a natural number: "
);
int
num
=
0
;
try
{
Scanner
sc
=
new
Scanner
(
System
.
in
);
num
=
sc
.
nextInt
();
sc
.
close
();
}
catch
(
InputMismatchException
e
) {
outputAndEnd
(
"Input not valid, expected a natural number."
);
// Error message for all non numerical inputs
}
if
(
num
<
0
) {
outputAndEnd
(
"Input not valid, natural number expected"
);
// Error message for all negative inputs
}
else
if
(
num
<
2
) {
outputAndEnd
(
"0 and 1 are neither prime nor composite"
);
// Info message for 0 and 1
}
// Check if the given number is divisible from any number between 2 and num/2, if so, its composite
for
(
int
i
=
2
;
i
<=
num
/
2
;
i
++) {
if
(
num
%
i
==
0
) {
outputAndEnd
(
num
+
" is not a prime number."
);
// Output result and exit as we found one divisor other than 1 and itself
}
}
// The number has exit the loop with no divisors, which means it is a prime number, print success message.
outputAndEnd
(
num
+
" is a prime number."
);
}
// A method to print the given message and exit the program
private
static
void
outputAndEnd
(
String
message
) {
System
.
out
.
println
(
message
);
// output the given message
System
.
exit
(
0
);
// exit the program
}
}
Back
|
FazBrowse Home
|
New Git URL