Hugo K
Hugo K

Reputation: 75

Arduino multiplication error, +ve * +ve becomes -ve

I am benchmarking different platforms and languages with a simple script that emulates the Collatz conjecture. During testing I found that my arduino gets stuck on seed 447 where multiplying int 13121 by three yields -26173.

My initial code was `

//made by Hugo K 
//jun 13 2014




void setup()
{
  Serial.begin(9600);
  while (!Serial)
  {
    ;//wait for serial to connect
  }

}


void loop()
{
  unsigned long starttime;
  starttime = millis();
  for (int i = 1; i <= 500; i++)
  {
    int a = i;
    while (a != 1)
    {
      if (a%2 == 0)
      {
        a = a/2;
      }
      else
      {
        a = (a*3) + 1;
      }
      //Serial.println(a);
    }

  }
  Serial.println(millis() - starttime);
}`

And later confirmed by `

void setup()
{
 Serial.begin(9600);
 while(!Serial)
 {
 }

}


void loop()
{
  int i = 13121;
  Serial.println(i *3);

}`

Is there something wrong with the atmega microcontroller in there? or is there a problem with int 13121 that upsets traditional multiplication ?

Upvotes: 1

Views: 140

Answers (2)

Oleg Gryb
Oleg Gryb

Reputation: 5249

Since the sizeof(int) == 2 in this architecture, the max positive integer is 0x7FFF (32,767), while in your case it's 39363.

Using unsigned int will increase your max to 0xFFFF

Using unsigned long - to 0xFFFFFFFF

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798814

There's something wrong with your expectation that int is 32 bits. With AVR, int is only 16 bits; use long if you want 32 bits.

Upvotes: 0

Related Questions