Programming Challenge #1 — Primes

Code difficulty: 3/10
Math difficulty: 4/10

In his challenge I ask that you do the following things:

Create a program that will:

  1. Allow a user to input a number
  2. Allow the user to see if the number is prime or not
  3. If the number is not prime, tell the user what number it is divisible by
  4. Use a function to process whether or not the value is prime (this idea will be used in a future challenge
  5. Use double or Long for increased number length

Concepts used: Functions, variables, loops, arithmatic functions, breaks, boolean

You should be able to do this by: Lesson 33

My solution: http://ideone.com/AKmCm (spoilers- Don’t look unless you are really stuck!)

Please note that my solutions are not checked thoroughly, and should only be used for reference. They are often non-optimal solutions that could be improved upon (by you!). I keep these intentionally rough for just that reason.

3 comments

  1. MegaHertz says:

    I think the example code has an off by one error. The for loops should be:

    for(int i=6; i<=testUpTo; i+=6)
    or
    for(int i=6; i<testUpTo+1; i+=6)
    instead of:

    for(int i=6; i<testUpTo; i+=6)

    notice that if you enter in a number that is the square of a prime that is congruent to 5 modulo six, it will incorrectly identify that number as prime. ie. 121 (11*11) and 289(17*17) are both not prime, but this program says they are.

  2. ranunky says:

    You solution doesn’t tell the user what primes their input is divisible by in the case of non-prime input, requirement #3 for the program.

    • Damien says:

      I ended up taking that out due to the amount of output it would take. It would be fairly easy to do this using either an array or an arraylist and just do a .add whenever you hit a number that isn’t divisible in your for loop.

Leave a Reply

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

*