File tree Expand file tree Collapse file tree 2 files changed +62
-0
lines changed
src/com/codefortomorrow/intermediate/chapter11 Expand file tree Collapse file tree 2 files changed +62
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .codefortomorrow .intermediate .chapter11 .practice ;
2
+
3
+ /*
4
+ Write a method called isPrime which returns
5
+ true if the given integer is prime and false otherwise.
6
+ Bonus points for writing JavaDoc comments for the method.
7
+
8
+ Test your isPrime method in the main method by
9
+ calling it at least 3 times and printing the result.
10
+
11
+ Solution from Listing 6.7, Introduction to Java Programming (Comprehensive),
12
+ 10th ed. by Y. Daniel Liang
13
+ */
14
+
15
+ public class IsPrime {
16
+ public static void main (String [] args ) {
17
+ // test isPrime method here
18
+ }
19
+
20
+ // write isPrime method here
21
+ }
Original file line number Diff line number Diff line change
1
+ package com .codefortomorrow .intermediate .chapter11 .solutions ;
2
+
3
+ /*
4
+ Write a method called isPrime which returns
5
+ true if the given integer is prime and false otherwise.
6
+ Bonus points for writing JavaDoc comments for the method.
7
+
8
+ Test your isPrime method in the main method by
9
+ calling it at least 3 times and printing the result.
10
+
11
+ Solution from Listing 6.7, Introduction to Java Programming (Comprehensive),
12
+ 10th ed. by Y. Daniel Liang
13
+ */
14
+
15
+ public class IsPrime {
16
+ public static void main (String [] args ) {
17
+ System .out .println (isPrime (5 )); // true
18
+ System .out .println (isPrime (1 )); // false
19
+ System .out .println (isPrime (56 )); // false
20
+ }
21
+
22
+ /**
23
+ * Check whether number is prime
24
+ * @param number number to check if prime
25
+ * @return true if the number is prime
26
+ */
27
+ public static boolean isPrime (int number ) {
28
+ if (number <= 1 ) {
29
+ return false ;
30
+ }
31
+
32
+ // only need to check divisors up to number / 2
33
+ // because after that the factors "repeat"
34
+ for (int divisor = 2 ; divisor <= number / 2 ; divisor ++) {
35
+ if (number % divisor == 0 ) { // primes only divisible by 1 and itself
36
+ return false ; // number isn't a prime
37
+ }
38
+ }
39
+ return true ; // number is a prime
40
+ }
41
+ }
You can’t perform that action at this time.
0 commit comments