Question

I wrote a program in java and php. In which a loop runs 64 times. And keep adding n to n:

Java Code:

  public static void main(String[] args) {
    double n = 1;
    double p = 1;
    for(int i = 1;i <= 64;i++){
        n = n + n;
        p = p + n;
    }
    System.out.println(p);
}

PHP code:

<?php
    $n = 1;
    $p = 0;
    for($i = 1;$i <= 64;$i++){
        $n = $n + $n;
        $p = $p + $n;
    }
    echo($p);

?>

And the output of both of these is:

3.6893488147419E+19

Now I want to know is it possible to convert this big float to int? if yes, Then how. In both languages.

Était-ce utile?

La solution

I would use the BigInteger type,

public static void main(String[] args) {
    BigInteger n = BigInteger.ONE;
    BigInteger p = BigInteger.ONE;
    for(int i = 1;i <= 64;i++){
        n = n.add(n);
        p = p.add(n);
    }
    System.out.println(p);
}

Output is

36893488147419103231

Edit Based on your comment, you really wanted something more like The Legend of the Chessboard -

BigInteger n = BigInteger.ONE;
BigInteger p = BigInteger.ZERO;
BigInteger TWO = new BigInteger("2");
for (int i = 1; i <= 64; i++) {
    StringBuilder sb = new StringBuilder();
    sb.append("For square #: " + i);
    sb.append(", Grains on square: " + n);
    p = p.add(n);
    n = n.multiply(TWO);
    sb.append(", Running Total: " + p);
    System.out.println(sb.toString());
}

Autres conseils

The number is too large to fit in a long. To get the closest integral approximation, convert the double to a BigInteger by way of a BigDecimal:

BigDecimal bd = BigDecimal.valueOf(p);
BigInteger bi = bd.toBigInteger();

However, to get an exact result, perform all the calculations using BigIntegers:

import static java.math.BigInteger.ONE;

BigInteger n = ONE;
BigInteger p = ONE;
for (int i = 1; i <= 64; i++) {
    n = n.add(n);
    p = p.add(n);
}
System.out.println(p);

The difference between the approximate and exact values is:

36893488147419103000
36893488147419103231

Java: Math.round(float), PHP: round(value,precision) However you will precision

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top