SARose
SARose

Reputation: 3725

Running a For Loop over billion times in Java

Is there a way to run a for loop where

i > INT_MAX_VALUE

I know that INT_MAX_VALUE is equal to 2,147,483,647

I can't imagine it being impossible but if it is there a work around?

Thanks a lot guys.

Upvotes: 1

Views: 3028

Answers (4)

Rahamath
Rahamath

Reputation: 531

BigInteger bi_ = new BigInteger("1000000000000000000");
    for(;true;) {
        System.out.println(bi_);
        bi_ = bi_.add(new BigInteger("1"));
        if(bi_.equals(new BigInteger("1000000000000000000000000000"))) {
            System.out.println(bi_);
            break;
        }
    }
 Above for loop start from 1 quintillion and end with 1 octillion
// One quintillion --> 10^18 = 1,000,000,000,000,000,000
// One octillion   --> 10^27 = 1,000,000,000,000,000,000,000,000,000

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881783

There are other data types with more range than a simple int. For example:

for (long num = 0; num < 1000000000000L; num++) ...

That'll get you up to about 9 quintillion (9,223,372,036,854,775,807). If you need more than that, you may want to consider not so much the range as the time it's going to take to run the loop - at a billion iterations per second, it'll take a little over 290 years :-)

Upvotes: 6

Titi Kokov
Titi Kokov

Reputation: 127

Looping has nothing to do with integer types in general.But in this case you can simply use long type instead of int type.

for(long i=0;i<max;i++){  
// as max is long type and max can take values upto 9,223,372,036,854,775,807
//code
}

Upvotes: 4

rgettman
rgettman

Reputation: 178283

You must make i a long, so it can take values greater than Integer.MAX_VALUE. If you're using a literal number in your loop's condition, append 'L' to use a long literal so you can use a literal value greater than Integer.MAX_VALUE.

Upvotes: 1

Related Questions