THIS month's offering shows a rather elegant, though somewhat inefficient, technique for checking for prime numbers. You'll no doubt remember from school that prime numbers are numbers that have no integer divisor apart from 1. - 20,30 Give you the chance to decide where the search for primes stops. Don't pick too high a figure or you'll run out of memory.
- 40 Dimensions an array with one element for each of the integers -whole numbers - up to limit.
- 50-80 Form a loop which goes through each element in turn putting the current value of index into number (index). This means that number(1) will hold 1, number(2) contains 2 and so on up to numberiUmit) which holds limit.
- 90 Stores the square root of limit in the variable upperBound. If you've already checked all the numbers up to upperBound to see whether they're primes there's no point in going any further. Think about it!
- 110-130 The FOR... NEXT loop works through all the values from 2 to upperBound to see if they are primes. Each time round the loop the subroutine that actually does the work is called.
- 140-170 Yet another loop, this time displaying all the primes found.
- 160 If the element has a value of less than 0 it's ignored. As the subroutine gives non-primes the value -1 this means that only the primes are displayed.
- 190-240 The subroutine that does the work.
- 200 If the element is less than 1 (in fact the way the program works means that it can only be -1 or a positive integer) the number is non-prime and the routine ends.
- 210-230 Should the element have a value greater than 1 it means that it is a prime. This element is left intact but the loop ensures that its multiples, which can't be primes, are marked with -1.
The logic is that if 3 is a prime then 6, 9, 12 and so on can't be. By the time the program has worked its way through all the elements in the array the non-primes will be marked. CWTA ★ AMSTRAD CPC ★ DOWNLOAD ★ |
|
CPCrulez[Content Management System] v8.7-desktop/c Page créée en 466 millisecondes et consultée 978 foisL'Amstrad CPC est une machine 8 bits à base d'un Z80 à 4MHz. Le premier de la gamme fut le CPC 464 en 1984, équipé d'un lecteur de cassettes intégré il se plaçait en concurrent du Commodore C64 beaucoup plus compliqué à utiliser et plus cher. Ce fut un réel succès et sorti cette même années le CPC 664 équipé d'un lecteur de disquettes trois pouces intégré. Sa vie fut de courte durée puisqu'en 1985 il fut remplacé par le CPC 6128 qui était plus compact, plus soigné et surtout qui avait 128Ko de RAM au lieu de 64Ko. |
|
|