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.
Source Code in text format (See below images of code for indentation):
import java.util.*;
/*class definition*/
public class primeCount
{
/*main method*/
public static void main(String[] args)
{
/*Scanner class to read input from the user*/
Scanner read=new Scanner(System.in);
/*variables*/
int count,from,to;
/*read two numbers from user*/
System.out.print("Enter starting number: ");
from=read.nextInt();
System.out.print("Enter ending number: ");
to=read.nextInt();
/*method call*/
count=countPrimes(from,to);
/*print count*/
System.out.println("The number of primes between "+from+" - "+to+" is: "+count);
}
/*method definition*/
public static int countPrimes(int from, int to)
{
int count=0;
/*using loop count prime numebers*/
for(int i=from;i<=to;i++)
{
/*check for prime using method call and increment count*/
if(isPrime(i))
count++;
}
/*return count*/
return count;
}
public static boolean isPrime(int i)
{
int k;
/*variable to check prime or not*/
boolean check=true;
if(i==0||i==1)
check=false;
for(k=2;k<i;k++)
{
/*check for divisors*/
if(i%k==0)
{
check=false;
break;
}
}
/*return check*/
return check;
}
}
Source Code:
Output: