Arduino calculate prime numbers 2010-05-03 10:27am
I wrote some code to stress test my Arduino. The code below will make your arduino calculate prime numbers.
void setup() {
Serial.begin(9600);
}
long i = 2; // Start at 2
void loop() {
char output[50];
int prime = is_prime(i); // Check if the number we're on is prime
char* status;
if (prime) { status = "yes"; }
else { status = "no"; }
if (prime == 1) {
Serial.print("Checking ");
Serial.print(i);
Serial.print(" for prime ");
Serial.print(status);
Serial.print(" in ");
Serial.print(millis() / 1000.0f);
Serial.println(" seconds");
}
i++;
}
int is_prime(int num) {
// Only have to check for divisible for the sqrt(number)
long upper = sqrt(num);
// Check if the number is evenly divisible (start at 2 going up)
for (long cnum = 2; cnum <= upper; cnum++) {
int mod = num % cnum; // Remainder
if (mod == 0) {
return 0;
} // If the remained is 0 it's evenly divisible
}
return 1; // If you get this far it's prime
}




