Approximately 2.85 billion objects were created.
Each time the loop executes count = count.add( BigInteger.ONE )
a new object is created for count.
Each time count.remainder( seven ) executes a new object is created.
Each time the loop executes sum = sum.add( count )
a new object is created for sum.
This happens for 6 out of 7 loop iterations (roughly).
BigInteger objects are immutable.
Every arithmetic operation creates a new object for the result.
Object creation takes time and memory.
If you don't need big integers, don't use BigInteger.
If the values fit into a long, you could do this:
class SumLoop
{
public static void main ( String[] args )
{
long count = 2000000000L ;
long end = 3000000000L ;
long sum = 0L;
while ( count <= end )
{
if ( count%7 != 0 )
{
sum += count;
}
count++ ;
}
System.out.println( "The sum: " + sum );
}
}
C:\>java SumLoop
The sum: 2142857145142857143
This takes just a few seconds to run.
(Review Question: ) Is 13 a prime number?