Calculate Prime Numbers using an ARDUINO Board
Following example uses an Arduino board to calculate a prime number list, starting from one.
It shows the result using serial port communication.
BUILDING AND RUNNING THE CODE
You should copy this code into your Arduino IDE window, compile it (C-R), upload the code into the board (C-U) and to see the result open the serial monitor (C-Shift-M).
If everything goes fine your serial monitor will show a prime on each line every time it is calculated. Maximum prime able to be calculated depends on long type maximum value.
long number = 3; void setup() { Serial.begin(9600); Serial.println("#"); Serial.println("1"); Serial.println("2"); } void loop() { int is_prime = 1; long i = 3; long top = sqrt(number); while (i<top) { if (number%i == 0) { is_prime = 0; break; } i++; } if (is_prime) { Serial.println(number,DEC); } number += 2; }
Within setup function, it shows 1 and 2 primes. It then starts calculating in the main loop using number 3.
Primality test here consists on performing divisions and checking the remainder. It is not needed to test with every divisor, when square root is reached we know it is a prime.
When a prime number is found it is sent over serial line.
As we start calculations with number three, we can skip all even numbers.
YOU MAY ALSO BE INTERESTED IN:
Install and run a program in Arduino using 64 bits Ubuntu (lucid) distro