Search code examples
carduinoarduino-unoarduino-ide

Arduino does not run with high values


I have the code below (cod01) that I need to convert into code for Arduino (cod02). It deals with the Eratosthenes Sieve algorithm (finding prime numbers from an upper limit). The cod01 works perfectly and has already been tested with values above 1000000 and always runs. I converted it to Arduino but it only works until 1768. I need it to work until 2000, can someone help me?

//cod01
#include <stdio.h>
#include <math.h>
#include <stdlib.h>

#define MAX 7
 
int main(){
  int i,j;
  int limite;
  char ehprimo[MAX];
  int cont=0;

  for(i=2;i<MAX;i++) ehprimo[i]=1;
  limite = (int)sqrt(MAX);
  for(i=2;i<=limite;i++){
    if(ehprimo[i]){
      for(j=i*i;j<MAX;j=j+i)
        ehprimo[j] = 0;
    }
  }

  for(i=2;i<MAX;i++){
    if(ehprimo[i]){
      printf("%d\t",i);
    }
  }
return 0;
}

.

//cod02
#define MAX 2000
  
  int i,j;
  int limite;
  char ehprimo[MAX];
  int cont=0;

void setup() {

  Serial.begin(9600);
  
  for(i=2;i<MAX;i++) ehprimo[i]=1;
  limite = (int)sqrt(MAX);
  for(i=2;i<=limite;i++){
    if(ehprimo[i]){
      for(j=i*i;j<MAX;j=j+i)
        ehprimo[j] = 0;
    }
  }

   for(i=2;i<MAX;i++){
    if(ehprimo[i]){
      Serial.print("\t");
      Serial.print(i);
    }
  }
  
}

void loop() {

}

Solution

  • Your codes simply requires to much RAM.

    The Arduino Uno (with an ATmega328P µC) only has 2048 Byte SRAM.

    If you reserve 2000 Byte with the lines

    #define MAX 2000
    char ehprimo[MAX];
    

    There is not enough left for the stack and the Arduino Framework.

    You must either reduce your memory consumption or choose a µC with more SRAM.