0

The task is classical: calculate the number of rabbit pairs after 30 months, taking into account that each mature pare gives three young pair. The code is next:

    int young = 1;
    int mature = 0;  
    for(int n=2; n<=31; n++)
    {
        int take_away=young;
        young=3*mature; 
        mature=mature+take_away;
        System.out.println("month:"+n+"\t"+"mature\t"+mature+"\t"+"young\t"+young+"\n");
        if(n==31)System.out.println(mature+take_away);
    }

Here's the problem:

Initially everything is great:

month:2 mature 1 young 0

month:3 mature 1 young 3

month:4 mature 4 young 3

month:5 mature 7 young 12

Starting from 28th month output looks like:

month:28 mature 1674257764 young -2113786333

where does the minus come from?

Community
  • 1
  • 1
  • Change int to long. The range of int is getting exceeded. – Nicholas K Sep 19 '18 at 18:14
  • We basically use 2s complement numbers now, when a number gets very big the binary reaches the most significant digit, that number looks exactly like a negative number and the computer treats it that way. – Tatarize Sep 19 '18 at 18:28

1 Answers1

1

You use int and new number is more than Integer.MAX_VALUE. Do use long instead.

Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35