counter = x % 7 == 0 && x != 7 ? counter + 1 : counter;
counter = x % 11 == 0 && x != 11 ? counter + 1 : counter;
counter = x % 13 == 0 && x != 13 ? counter + 1 : counter;
counter = x % 17 == 0 && x != 17 ? counter + 1 : counter;
counter = x % 19 == 0 && x != 19 ? counter + 1 : counter;
document.write(counter == 0 ? "Prime number." :
"Not a prime number.");
The program simply counts the number of tim es the d ivision leaves a remainder of
zero. If there’s no such division, the tested number is a prime nu mber. Of course,
we don’t want to count situations where the number is divided by itself, which also
returns a zero remainder. That’s why we included the inequality comparisons.
Professor: Good. I see that you tested only divisions by prime numbers. There’s
really no need for testing with o ther numbers. For example, if a number is evenly
divisible by four, then it must also be evenly divisible by two. Thus you don’t need
to test the division by four. The same goes for six—if the number is evenly d ivisible
by six, then it must also be evenly divisible by two and three, and there’s no need to
divide by six.
Your program can in fact test the numbers up to 361 because you must only try the
divisions with numbers that are less than o r equal to the square root o f the tested
number. Observe that, if a number n is a product of two positive integers, o nly one
of them can be greater than the square root of n. So, if there existed a divisor greater
than the square root of n, then a divisor smaller than the square root of n would also
exist a nd yo u would already have found it.
Before we start today’s work I want you to understand a fundamental difference be-
tween the two tasks you had for your homework. The first one could be solved using
a single test, while the second one r equired repeated testing. This ca nnot be done
by simp ly writing many lines of co de because you don’t know how many times the
test should be repeated. This information is not available at the time of writing the
progr am. Besides, just copying and pasting the same code is not programming. For-
tunately, there are tools that allow for automated repetition of tasks, and that’s one of
the top ic s of today’s meeting.
Mike: One question: sometimes you write a semicolon at the end of a line and some-
times you don’t. Is there a rule so we know exactly where to put a semicolon? We
experimented and discovered that semicolons are not necessary.
Professor: A semicolon terminate s a statement. Which brings us to another important
topic in JavaScript.
7.2 Statements
Professor: So far we’ve only been working with expressions. Recall that an expres-
sion is evaluated in o rder to return a value. However, technically spea king, you need a
statement in order for that to happen. That is similar to English phrases, which shou ld
be put into sentences. And just as sentences are terminated and separated fro m each
128 Meeting 7. Controlling Program Flow