HackerRank: Shizuka and the Campus Placements
Shizuka has taken part in the Campus Placement drive taking place in her college. She has been studying all week for it. She has almost completed the syllabus and is left with just one problem. She needs to find Prime numbers within the given range in the last remaining problem. Help her out by finding it's solution.
NOTE: If the range does not exist, print "Invalid Input".
Input Format
Two integers, a and b (Start and end of the range)
Constraints
None
Output Format
All the prime numbers in the given range [a,b] separated by spaces.
Sample Input 0
1 10
Sample Output 0
2 3 5 7
Explanation 0
2, 3, 5, 7 are the prime numbers in 1 to 10
Sample Input 1
18 30
Sample Output 1
19 23 29
Explanation 1
19 23 29 are the prime numbers in 18 to 30
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b= sc.nextInt();
if(b < a)
System.out.println("Invalid Input");
else{
if(a<0)
a=0;
if(b<0)
b=0;
for(int i = a; i<= b; i++){
isPrime(i);
}
}
}
public static void isPrime(int n){
int num =n;
if(num == 1){
return;
}
int[] prime ={2,3,5,7};
boolean flag = true;
for(int i =0; i< 4; i++){
if(num % prime[i] == 0){
if(num == prime[i])
flag = true;
else
flag = false;
}
}
if(flag== true){
System.out.print(num +" ");
}
}
}