Monday, September 12, 2016

JAVA HOW TO PROGRAM, DEITEL: CHAPTER SIX SOLUTIONS



Question: Prime Number


A positive integer is prime if it’s divisible by only 1 and itself. For example, 2, 3, 5 and 7 are prime, but 4, 6, 8 and 9 are not. The number 1, by definition, is not prime.

a) Write a method that determines whether a number is prime.
b) Use this method in an application that determines and displays all the prime numbers less than 10,000. How many numbers up to 10,000 do you have to test to ensure that you’ve found all the primes?
c) Initially, you might think that n/2 is the upper limit for which you must test to see whether a number n is prime, but you need only go as high as the square root of n. Rewrite the program, and run it both ways.




Solution: Prime Number


// Author: Free Coder
//www.freecoder247.blogspot.com

public class PrimeNumberGenerator {
public static void main(String args[]) {

System.out.println(isPrimeNumber(11));
System.out.println(isPrimeNumber(22));
System.out.println(isPrimeNumber(37));
System.out.println(isPrimeNumber(7));

System.out.println("\n");
System.out.println(isPrimeNumberMethod2(3));
System.out.println(isPrimeNumberMethod2(43));
System.out.println(isPrimeNumberMethod2(23));
System.out.println(isPrimeNumberMethod2(88));

// Here 120 is an upper limit
generatePrimeNumbers(120);
}

private static boolean isPrimeNumber(int number) {
System.out.println("Prime check started for number: " + number);

// Loop starts from 2
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
return false;
}
}
  return true;
}

 // Another way to check if Number is Prime
 public static boolean isPrimeNumberMethod2(int number) {

  System.out.println("Prime check started for number: " + number);

boolean prime = true;
int limit = (int) Math.sqrt(number);

for (int i = 2; i <= limit; i++) {
if (number % i == 0) {
prime = false;
break;
}
}

  return prime;
}

public static void generatePrimeNumbers(int upperLimit) {

System.out.println("\nGenerating all prime number between 2 to " + upperLimit);

for (int i = 2; i < upperLimit; i++) {

boolean isPrime = true;

// check to see if the number is prime
for (int j = 2; j < i; j++) {

if (i % j == 0) {
isPrime = false;
break;
}
}
 

// print the number
if (isPrime)
System.out.print(i + " ");
}
}

}



1 comment:

  1. Free Spins & No Deposit Bonuses from Casino Site - ChoEgocasino
    Best Online septcasino Casino Bonuses From Casino Site ✚ No Deposit choegocasino Free หาเงินออนไลน์ Spins ➜ Deposit Bonus Code ✚ No Deposit Required ✓ Free Spins Bonus Code.

    ReplyDelete