Sunday, January 6, 2019

How to find Prime Number

How to find Prime Number in Java


Learn:
1. check the given number is prime or not.
2. print all the prime numbers upto a given a number
3. write different test cases




Code:

package Questions;

public class PrimeNumber {
//2 is the lowest prime number
//3
//num = 20
public static boolean isPrimeNumber(int num){
//edge/corner cases:
if(num<=1){
return false;
}
for(int i=2; i<num; i++){
if(num % i == 0){
return false;
}
}
return true;
}
public static void getPrimeNumbers(int num){
for(int i=2; i<=num; i++){
if(isPrimeNumber(i))
System.out.print(i + " ");
}
}
public static void main(String[] args) {
System.out.println("2 is prime number: "+ isPrimeNumber(2));
System.out.println("3 is prime number: "+ isPrimeNumber(2));
System.out.println("10 is prime number: "+ isPrimeNumber(10));
System.out.println("17 is prime number: "+ isPrimeNumber(17));

System.out.println("0 is prime number: "+ isPrimeNumber(0));
System.out.println("1 is prime number: "+ isPrimeNumber(0));

System.out.println("-3 is prime number: "+ isPrimeNumber(-3));
getPrimeNumbers(7);
getPrimeNumbers(13);
getPrimeNumbers(20);



}



}










2 comments:

Featured Post

Advanced Selenium Webdriver Interview Questions and Answers in Java

Advanced Selenium Webdriver Interview Questions and Answers in Java Selenium WebDriver - QA Here is the list of Selenium Inte...