|
Implication:
|
|
|
x = 1;
while ( x <= n ) // Run x = 1, 2, ..., n
{
Invariant:
We have found all divisors of n that are < x
x = the current divisor that we will try
if ( n % x == 0 )
{ // x is a divisor of n
System.out.println(x); // Print x (because it's a divisor)
}
x++; // Make sure we more to the next number !!
// or else: infinite loop !!!
}
Invariant when loop ends:
We have found all divisors of n that are <= n
|
Note:
|
min = min(a,b);
a = 1;
while ( a <= min ) // Run a = 1, 2, ..., min(x,y)
{
Invariant:
We have found all common divisors of a and b that are < x
x = the current common divisor that we will try
if ( x % a == 0 && y % a == 0 )
{ // a is a divisor of x and y
System.out.println(a); // Print a (because it's a common divisor)
}
a++; // Make sure we move to the next number !!
// or else: infinite loop !!!
}
Invariant when loop ends:
We have found all common divisors of a and b that are <= min
|
f = 2;
while ( x > 1 )
{
Invariant:
x = the number that remains to be factor
and we have removed all factors < f
if ( x % f == 0 )
{ // f is a factor of x
System.out.println(f); // Print f (because it's a divisor)
x = x / f; // Remove factor f from x
}
else
{
f++; // Use next number as factor
}
}
Invariant when loop ends:
The number that remains to be factored = 1
and we have removed all factors including the largest factor
(I.e.: we have found all the factors)
|
|
|