HackerRank Java- Prime Checker




You are given a class Solution and its main method in the editor. Your task is to create a class Prime. The class Prime should contain a single method checkPrime.

The locked code in the editor will call the checkPrime method with one or more integer arguments. You should write the checkPrime method in such a way that the code prints only the prime numbers.

Please read the code given in the editor carefully. Also please do not use method overloading!



  1. import java.io.*;
  2. import java.util.*;
  3. import java.text.*;
  4. import java.math.*;
  5. import java.util.regex.*;
  6. import java.lang.reflect.*;
  7. import static java.lang.System.in;
  8. class Prime {
  9. void checkPrime(int... numbers) {
  10. for (int num : numbers) {
  11. if (isPrime(num)) {
  12. System.out.print(num + " ");
  13. }
  14. }
  15. System.out.println();
  16. }
  17. boolean isPrime(int n) {
  18. if (n < 2) {
  19. return false;
  20. } else if (n == 2) { // account for even numbers now, so that we can do i+=2 in loop below
  21. return true;
  22. } else if (n % 2 == 0) { // account for even numbers now, so that we can do i+=2 in loop below
  23. return false;
  24. }
  25. int sqrt = (int) Math.sqrt(n);
  26. for (int i = 3; i <= sqrt; i += 2) { // skips even numbers for faster results
  27. if (n % i == 0) {
  28. return false;
  29. }
  30. }
  31. return true;
  32. }
  33. }
  34. public class Solution {
  35. public static void main(String[] args) {
  36. try{
  37. BufferedReader br=new BufferedReader(new InputStreamReader(in));
  38. int n1=Integer.parseInt(br.readLine());
  39. int n2=Integer.parseInt(br.readLine());
  40. int n3=Integer.parseInt(br.readLine());
  41. int n4=Integer.parseInt(br.readLine());
  42. int n5=Integer.parseInt(br.readLine());
  43. Prime ob=new Prime();
  44. ob.checkPrime(n1);
  45. ob.checkPrime(n1,n2);
  46. ob.checkPrime(n1,n2,n3);
  47. ob.checkPrime(n1,n2,n3,n4,n5);
  48. Method[] methods=Prime.class.getDeclaredMethods();
  49. Set<String> set=new HashSet<>();
  50. boolean overload=false;
  51. for(int i=0;i<methods.length;i++)
  52. {
  53. if(set.contains(methods[i].getName()))
  54. {
  55. overload=true;
  56. break;
  57. }
  58. set.add(methods[i].getName());
  59. }
  60. if(overload)
  61. {
  62. throw new Exception("Overloading not allowed");
  63. }
  64. }
  65. catch(Exception e)
  66. {
  67. System.out.println(e);
  68. }
  69. }
  70. }




codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube