1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: Comp Sci Question

  1. Oct 11, 2007 #1
    1. The problem statement, all variables and given/known data
    The problem is to find all the prime numbers between one and one-hundred and print them out in pseudocode.

    Here is my attempt. The problem is that when it's false, isPrime will be false but when it tries to divide by the next number and it is true, it makes isPrime true. I'm not sure how to fix this. Help!

    bool isPrime <-- true
    int i
    int j

    for i <-- 1 to 100
    for j <--2 to 10
    if (i=1)
    if (i =2)
    print i
    if (i = j)
    if (i % j != 0 AND i!=j)
    isPrime= true
    if (i % j = 0)
    isPrime = false
    if (isPrime = true)
    print i
  2. jcsd
  3. Oct 11, 2007 #2

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    Some comments, the big problem is last.

    Why are you starting at 1, or even 2? You know 1 is not prime and 2 is prime, as you have these hardcoded as exceptional cases. Print that 2 is prime and start at 3. All that those exceptional cases do is add complexity to the program. A lot (an awful lot) of programming shops measure the "cyclomatic complexity" of code. A lot (not quite as many, but still a lot) of programming shops specifically ban the use of "continue".

    Much better would be to end this loop at sqrt(i), or if that is not acceptable, at i-1. Doing either makes a lot more sense than ending at 10.

    This is the big problem. There are two problems here. First, any number j that divides some other number i means i is not prime. This logic does not test for primality! Another problem: You have a fall through case (i.e., there is no final else). Once again, many programming shops view this as a sign of sloppy programming. Even if a final else is not needed, it is better to put one in that explicitly does nothing. Doing so shows that the programmer has thought about all of the cases.

    Bottom line: You really need to fix the primality testing logic. Fixing the loop bounds is a good idea as well.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook