Physics and Astronomy |

Back to top
On this page
Contents ## Example: a prime number testHere we show a complete program, which uses the logical
&& in its A few points are worth noting: - The test to see if an integer is an exact multiple of another
is:
`int1 % int2 != 0` - As mentioned in the notes we
are allowed to use &&, || etc. inside the controlling expression
of a
`while()`or`for()`loop. - The rules for converting positive floating-point numbers
to integers (discard the fraction), mean that the code:
int intvar; intvar = sqrt(5); sets `intvar`to be the largest integer less than or equal to the square root of 5, ie 2.
// // Print the lowest factor of an integer or say that it is prime. // Written to illustrate the while() loop // The basic algoritm is to try every possible factor up to the square // root of the number being looked at (the target) // #include <stdio.h> #include <math.h> int main() { int target, factor, maxfactor; target = 55; maxfactor = sqrt(target); // Largest factor we need to try factor = 2; while ( target % factor != 0 && factor <= maxfactor ) ++factor; // factor = factor + 1 if ( factor > maxfactor ) printf("%d is prime\n", target); else printf("\t%d is not prime, its lowest factor is %d\n", target, factor); return 0; } ## Optional: some details## Empty loopsWe could have chosen to write the main loop
using the for (factor = 2; target % factor != 0 && factor <= maxfactor; factor = factor + 1) ; This looks very strange as the loop body is empty: the test and iteration do all the work. ## Zero expressionsThe "logical" expressions used in control statements or as arguments to && or || are considered to be "true" if they are not equal to zero. Hence in the statement: if ( The " if ( Thus our while ( target % factor && factor <= maxfactor ) factor = factor + 1; ## Every prime number up to 1000 Any
// // Find the lowest factor of the integers 2 to 1000, or say it is prime. // The basic algoritm is to try every possible factor up to the square // root of the number being looked at (the target) // #include <stdio.h> #include <math.h> int main() { for (int target = 2; target <= 1000; ++target ) { int factor, maxfactor; maxfactor = sqrt(target); // Largest factor we need to try factor = 2; while ( target % factor != 0 && factor <= maxfactor ) ++factor; if ( factor > maxfactor ) printf("%d is prime\n", target); else printf("\t%d is not prime, its lowest factor is %d\n", target, factor); } return 0; } In this example the variables This example also illustrates that there are no restrictions
on how ## To think aboutThis program contains one loop inside another. Both loops are written in the simplest way possible and both could be sped up. How? What disadvantages might this have? |