-5

So I'm currently using this code to calculate the population growth:

import java.util.Scanner;

public class PopulationGrowth
{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int totalP = 0;

        System.out.print("Enter Starting Populatino: ");
        int startingP = sc.nextInt();

        System.out.print("Enter Growth Rate: ");
        int growthR = sc.nextInt();

        System.out.print("Enter amount of time it takes to achieve this growth: ");
        int timeI = sc.nextInt();

        System.out.print("Enter Total Amount of Time: ");
        int totalTime = sc.nextInt();

        int intervals = totalTime / timeI; 
        for(int i = 0; i < intervals; i++)
        {
            long finalP = startingP * growthR;
            System.out.println(finalP);
            growthR += growthR;
        }

    }

}

It works fine, but if I input a large number I get this output:

65536000
131072000
262144000
524288000
1048576000
2097152000
-100663296
-201326592
-402653184
-805306368
-1610612736
1073741824
-2147483648
0
0
0
0
0
0
0
0
0
0
0
0
0

Note, if you look at my code you could see that I tried using the long type, but unfortunately, that didn't work

My Question:

Is there a way for Java to print a large number without the use of long or double?

Joseph Attia
  • 306
  • 3
  • 17

1 Answers1

1

I tried using the long type, but unfortunately, that didn't work

long finalP = startingP * growthR;

As long as startingP and growthR are still int, this calculation will still be done using 32 bit integers (and only converted to 64 bit integers afterwards, when you already encountered overflow).

You can change all your variables to long. Then you will be able to work with larger numbers, but eventually those will also overflow.

Is there a way for Java to print a large number without entering the negatives and ultimately the 0s

Depending on your application needs, you may need to look at either infinite-precision BigInteger or floating point numbers such as double (which can represent much larger quantities, but with a loss of precision in the lower digits -- that seems acceptable here).

Thilo
  • 257,207
  • 101
  • 511
  • 656