main()
function main () {
print ("hello");
printPrimeNumbers (1, 100);
return 0;
}
function printPrimeNumbers (startNumber, maxNumber) {
var counter = startNumber;
while (counter < maxNumber){
if (isPrime(counter)) {
print (counter);
}
counter++;
}
return 0;
}
function isPrime (number) {
var prime = true;
if (number > 3){
if (number !== 0){
var i = (number-1)/2;
while (i>1) {
if (number % i == 0) {
prime = false;
return prime;
}
i--;
}
}
else {
prime = false;
}
}
return prime;
}
Basically, isPrime (number) is the function which is doing all the work at the moment. If the number is greater then 3 and not divisible by 2 then: see if it can be divided by any number smaller then itself. This number starts from itself divided by two to reduce the number.
Found this little site which gives nice little examples of small C programs
So far this works. It is in fact already optimised slightly with the:
if (number !== 0)
and
var i = (number-1)/2;
I havent actually read up on any optimisations anyone else has done. I think I'll carry on and when I get stuck I'll do some research.
My next main idea is to record all prime numbers starting from one up to the maxNumber. Then, to find out if the next one is a prime, just divide by all other primes before it. Should then not have to do as much work, perhaps by 3/4? The two down sides are that:
- I'd have to store these numbers somewhere
- I'd have to have all the primes up to the number you want to know whether is a prime or not.
Works pretty well.#include#define true 1#define false 0#define STARTNUM 1#define ENDNUM 100000000int printPrimes (int startNumber, int maxNumber);int isPrime (int number, int primesArray[], int numberOfPrimes);int main (int argc, const char * argv[]) {printf ("hello \n");printPrimes (STARTNUM, ENDNUM);return 0;}int printPrimes (int startNumber, int maxNumber) {int counter = startNumber;int numberOfPrimes = 0;int primesArray [100000];while (counter < maxNumber){if (isPrime(counter, primesArray, numberOfPrimes)) {printf ("%d\n" , counter);primesArray[numberOfPrimes] = counter;numberOfPrimes++;}counter++;}/*printf("Printing the Array of Primes\n");for (int c = 0; c < numberOfPrimes; c++) {printf("%d\n", primesArray[c]);}*/return 0;}int isPrime (int number, int primesArray[], int numberOfPrimes) {int prime = true;if (number <= 3){for (int i=1; i
if (number % primesArray[i] == 0) {prime = false;return prime;}}}return prime;}
A future idea is to find the frequency of primes and find a relationship. Perhaps taking it one step further and finding the frequency of frequencies. I'm not sure how to represent frequencies though?