Arduino calculate prime numbers

I wrote some code to stress test my Arduino. The code below will make your Arduino calculate prime numbers.

long start = 0;
long max_seconds = 30;
long i = 2; // Start at 2

void setup() {
  Serial.begin(9600); 

  while (!Serial) { }

  start = millis();
}

long found = 0; // Number we found

void loop() {
  int prime = is_prime(i); // Check if the number we're on is prime

  if (prime == 1) { 
    Serial.print(i);
    Serial.println(" is prime ");

    found++;
  }

  int running_seconds = (millis() - start) / 1000;

  if (max_seconds > 0 && (running_seconds >= max_seconds)) {
    Serial.print("Found ");
    Serial.print(found);
    Serial.print(" primes in ");
    Serial.print(max_seconds);
    Serial.println(" seconds");
    while(1) { } 
  }

  i++;
}

int is_prime(long num) {
  // Only have to check for divisible for the sqrt(number)
  int upper = sqrt(num);

  // Check if the number is evenly divisible (start at 2 going up)
  for (long cnum = 2; cnum <= upper; cnum++) {
    long mod = num % cnum; // Remainder

    if (mod == 0) { 
      return 0; 
    } // If the remainer is 0 it's evenly divisible
  }

  return 1; // If you get this far it's prime
}
Leave A Reply
All content licensed under the Creative Commons License