Snedden27
Snedden27

Reputation: 1930

why does modulus by a large number seem to give a wrong answer in Java

I am trying to find trailing numbers of zeros in a number, here is my code:

public class TrailingZeroes {
    public static void  bruteForce(int num){ //25
        double fact = num; //25
        int numOfZeroes = 0;

        for(int i= num - 1; i > 1; i--){
            fact = fact * (i);
        }
        System.out.printf("Fact: %.0f\n",fact); //15511210043330984000000000

        while(fact % 10 == 0){
          fact = fact / 10;
          double factRem = fact % 10;
          System.out.printf("Fact/10: %.0f\n",fact); //1551121004333098400000000
            System.out.printf("FactRem: %.0f\n",factRem); // 2?
          numOfZeroes++;
        }

        System.out.println("Nnumber of zeroes "+ numOfZeroes); //1

    }
}

As you can see the fact%10

Upvotes: 4

Views: 490

Answers (1)

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

You use floating point data type illegally.

The float and double primitive types in Java are floating point numbers, where the number is stored as a binary representation of a fraction and a exponent.

More specifically, a double-precision floating point value such as the double type is a 64-bit value, where:

  • 1 bit denotes the sign (positive or negative).
  • 11 bits for the exponent.
  • 52 bits for the significant digits (the fractional part as a binary).

These parts are combined to produce a double representation of a value.

For a detailed description of how floating point values are handled in Java, see the Section 4.2.3: Floating-Point Types, Formats, and Values of the Java Language Specification.

The byte, char, int, long types are [fixed-point][6] numbers, which are exact representions of numbers. Unlike fixed point numbers, floating point numbers will some times (safe to assume "most of the time") not be able to return an exact representation of a number. This is the reason why you end up with 11.399999999999 as the result of 5.6 + 5.8.

When requiring a value that is exact, such as 1.5 or 150.1005, you'll want to use one of the fixed-point types, which will be able to represent the number exactly.

As has been mentioned several times already, Java has a BigDecimal class which will handle very large numbers and very small numbers.


public static void bruteForce(int num) {    //25
    double fact = num;

    // precision was lost on high i
    for (int i = num - 1; i > 1; i--)
        fact *= i;

    String str = String.format("%.0f", fact);   //15511210043330984000000000
    System.out.println(str);

    int i = str.length() - 1;
    int numOfZeroes = 0;

    while (str.charAt(i--) == '0')
        numOfZeroes++;

    System.out.println("Number of zeroes " + numOfZeroes);  //9
}

Upvotes: 6

Related Questions