Nerozx
Nerozx

Reputation: 25

Java - long displays wrong values

I have to create a program that goes from 1 to 100 and calculates the separate product of the numbers that have from the division with 4 the rest 0, 1, 2, 3, so basically i have to calculate 4 different products.

I tried solving this problem in two ways both ways display the wrong results:

First attempt:

    public class prodmod4 {
public static void main(String[] args){
    int i, k=0;
    long P=1;
    while(k<4){
        for(i=1;i<=100;i++){
            if(i%4==k){
            P=P*i;
            }
        }
        System.out.printf("Produsul numerelor care au restul %d este: %d\n", k, P);
        i=1;
        P=1;
        k++;
    }
}
}

When i run this program it gives me:

The product of numbers with rest 0 is 0, rest 1 -6661643765781265135, rest 2 -2885954222765899776, rest 3 -9150527387120197261

Second attempt:

public class prodmod4v2 {
public static void main(String[] args){
    int i;
    long zero=1, unu=1, doi=1, trei=1;
    for(i=1;i<=100;i++){
        switch(i%4){
        case 0:
            zero=zero*i;
            break;
        case 1:
            unu=unu*i;
            break;
        case 2:
            doi=doi*i;
            break;
        case 3:
            trei=trei*i;
            break;
        default:
            break;
        }
    }
    System.out.printf("produsul numerelor care au resturile 0,1,2,3 sunt:\n zero:%d\n unu:%d\n doi:%d\n trei:%d\n", zero, unu, doi, trei);
}
}

When i run this i have the same output as in the first attempt.

Thank you in advance!

Upvotes: 0

Views: 1288

Answers (1)

Glorfindel
Glorfindel

Reputation: 22651

Your numbers are too big for a mere long, which supports numbers up to 2^63 - 1. When this happens, the result is said to overflow - which means that the results are not what you'd expect them to be. To solve this, you must use something that supports larger numbers, like BigInteger or BigDecimal.

Upvotes: 5

Related Questions