Java Reference
In-Depth Information
Table 5.1
Examples of Factors
Number
Factors
Smallest divisor
10
2 * 5
2
15
3 * 5
3
25
5 * 5
5
31
31
31
77
7 * 11
7
You don't start divisor at 1 because you are looking for the first divisor greater
than 1 . To refine this pseudocode, you must be more explicit about what makes a
divisor work. A divisor of a number has no remainder when the number is divided by
that divisor. You can rewrite this rule as the following pseudocode:
start divisor at 2.
while (the remainder of number/divisor is not 0) {
increase divisor.
}
This exercise is a use for the mod operator, which gives the remainder for integer
division. The following while loop performs the task:
int divisor = 2;
while (number % divisor != 0) {
divisor++;
}
One problem you will undoubtedly encounter when you write while loops is the
infamous infinite loop. Consider the following code:
int number = 1;
while (number > 0) {
number++;
}
Because number begins as a positive value and the loop makes it larger, this loop
will continue indefinitely. You must be careful when you formulate your while
loops to avoid situations in which a piece of code will never finish executing. Every
time you write a while loop, you should consider when and how it will finish
executing.
 
Search WWH ::




Custom Search