A.compareTo( B ) != 0
Or use equals().
How would you write a program that computes the sum of those integers from 2,000,000,000 to 3,000,000,000 that are not divisible by 7?
The counting loop can be implemented with a while
and the equals() method.
The not divisible by 7 part can be implemented with the remainder() method.
Here is the program:
import java.math.BigInteger;
class SumLoop
{
public static void main ( String[] args )
{
BigInteger count = new BigInteger( "2000000000" );
BigInteger end = new BigInteger( "3000000000" );
BigInteger seven = new BigInteger( "7" );
BigInteger sum = BigInteger.ZERO;
while ( count.compareTo( end ) <= 0 )
{
if ( !count.remainder( seven ).equals( BigInteger.ZERO ) )
sum = sum.add( count );
count = count.add( BigInteger.ONE );
}
System.out.println( "The sum: " + sum );
}
}
C:\> java SumLoop
The sum: 2142857145142857143
The program took about 3 minutes to run on my 2GHz computer.
How many objects were created during a run of the program?