Prime Checker

I mentioned in a previous post that I experienced some water problems in my home office after the water meter was replaced at home. The contractor who did the update stopped by yesterday afternoon with a powerful fan to help the small amount of water that had leaked into my office dry up. This morning the humidity from the carpet was gone. He also mentioned that they will replace the four books that got damaged by water. I will call this afternoon to return the fan and inform them of the four books.

I randomly selected the Prime Checker challenge at HackerRank. Read the requirements and spent time working on a solution. When I was ready to give it a try, noticed that it would not allow me to enter my solution. In addition, it seems that the scaffolding code has an issue and a message indicates that you need to address it. Not sure what is going on. Have to skip it because I am not able to enter my code.

That said; following are the test cases I used to generate my Solution using Java and the Eclipse IDE:

2
1
3
4
5

2 
2 
2 3 
2 3 5 

59
438
439
646
997

59 
59 
59 439 
59 439 997 

I did notice that depending on how the test numbers are presented, the scaffolding code does not seem to always display the correct answers.

Most methods used to determine if a number is prime number are based on variations of the Sieve of Eratosthenes.

The code for the Prime class follows:

	/*
	 * Requested class name for the challenge.
	 */
	static class Prime {
		
		/*
		 * Determine if this number is prime or not.
		 */
		private boolean isPrime(int n) {
			
			// **** number <= 1 are not prime ****
			if (n <= 1)
				return false;
			
			// **** 2 and 3 are prime ****
			if (n <= 3)
				return true;
			
			// **** skip multiples of 2 and 3 ****
			if ((n % 2 == 0) ||				// even
				(n % 3 == 0))				// start at 3
				return false;
			
			// **** start with 3 and increment by 2 ****
			int sr = (int)Math.sqrt(n);
			for (int i = 3; i <= sr; i += 2) {
				if (n % i == 0) {
					return false;
				}
			}
			
			// **** should be a prime ****
			return true;
		}
		
		
		/*
		 * Helper function to loop through the numbers and display primes
		 */
		void checkPrime(int... numbers) {
			
			// **** ****
			for (int n : numbers) {
				if (isPrime(n))
					System.out.print(n + " ");
			}
			System.out.println();
		}
	}

For ease of use, I placed a copy of my solution in my GitHub repository. If you get a chance take a look and let me know your thoughts.

If you have questions or issues with the contents of this post, or need help with a software development project, please feel free and leave me a note below. Notes will become public only if they are approved.

Keep on learning, experimenting and having fun creating great software;

John

Follow me on Twitter:  @john_canessa

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.