1 Reply Latest reply: Oct 7, 2008 9:46 AM by 843804 RSS

    Why is my code only working sometimes?

    843804
      This code is supposed to find the sum of the digits in the number 2^1000. However, it returns a decimal that is way off. And, for some reason, if 2^15 or 2^4 or other smaller exponents are used, the code works perfectly. Why is it taking exception with 1000 as an exponent??

      public double TwoToTheThousand() { //Adds all the digits together of the number 2^1000
      double tens = 10.0;
      double sum = 0.0;
      double num = Math.pow(2, 1000);
      double temp = Math.pow(2, 1000);
      for(double a = 0; a > -1; a++) {
      if(tens/10 > num)
      return sum;
      sum += ((num % tens)/(tens/10.0));
      num -= (temp%tens);
      temp = num;
      tens*=10.0;
      }
      return -1.0;
      }