Search code examples
javafibonacci

Why there are negatve numbers in the output?


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?


Solution

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