简体   繁体   中英

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.

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
}

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 :-)

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM