In: Computer Science
Java - Firstly, write a method, using the following header, that counts the number of prime numbers between from and to (inclusive). public static int countPrimes(int from, int to) For example, countPrimes(11,19) returns 4 since 11, 13, 17 and 19 are primes. You can assume that someone has already written the following function to determine is an integer is prime or not. public static boolean isPrime(int i) // returns true if i is a prime number Secondly, write a program that prompts the user to enter in two integers and then displays the number of prime numbers between the two integers by using the method you wrote above.
import java.util.Scanner; public class PrimesCount { public static boolean isPrime(int i) { for (int n = 2; n < i; n++) { if (i % n == 0) return false; } return i > 1; } public static int countPrimes(int from, int to) { int count = 0; for (int i = from; i <= to; i++) { if (isPrime(i)) ++count; } return count; } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter starting number: "); int start = in.nextInt(); System.out.print("Enter ending number: "); int end = in.nextInt(); System.out.println("Number of primes from " + start + " to " + end + " is " + countPrimes(start, end)); } }