1

i was trying to write a JAVA code to type these numbers

7, 87, 387, 5387, 95387, 195387, 4195387, 64195387, 464195387, 2464195387, 62464195387, 262464195387, 7262464195387, 27262464195387, 627262464195387, 5627262464195387, 75627262464195387, 575627262464195387, 4575627262464195387, 4575627262464195387

but when i wrote this code on netbeans it doesn't give me the sequence i want

 public class Sum30 {

    public static void main(String[] args) {
      double a;
   for(double i=2;i<100;i++){
      a=7;
   a=  (pow(3,a)%pow(10,i));
          System.out.println(a);
       }      

    }}

please tell me what is the wrong

3 Answers3

4

pow(3,a) produces huge numbers for big a values, so it will very soon (starting from Math.pow(3, 87)) produce values outside the range of double ("Infinity").

Also, your algorithm is entirely integer-based. You shouldn't use floating-point numbers for that calculation. Especially the loop index being double has a "smell" (even if it works in your case).

I recommend using int for the loop index and BigInteger for a:

public static void main(String[] args) {
    BigInteger a = BigInteger.valueOf(7);
    for (int i = 2; i < 100; i++) {
        a = (BigInteger.valueOf(3).pow(a.intValue()).mod(BigInteger.valueOf(10).pow(i)));
        System.out.println(a);
    }
}

Note that pow takes an int for the exponent, so this solution has a limit, too.

In order to avoid that limit, you may want to write your own pow function or use the combined modPow operation. Since you know beforehand that the result of your exponentiation will be modulo a (relatively small) number, you can use the combined operation that uses that knowledge to execute the exponentiation much more efficiently.

public static void main(String[] args) {
    BigInteger a = BigInteger.valueOf(7);
    for (int i = 2; i < 100; i++) {
        a = BigInteger.valueOf(3).modPow(a, BigInteger.valueOf(10).pow(i));
        System.out.println(a);
    }
}

This version doesn't have a limit apart from the available memory and the available processing time.

Community
  • 1
  • 1
mastov
  • 2,942
  • 1
  • 16
  • 33
1

You do this calculation in the loop:

 a=7;
 a=  (pow(3,a)%pow(10,i));

So pow(3,a) is always the same (2187), since a is always reset to 7. pow(10,1) quickly becomes much bigger than 2187, so the modulo becomes 2187. Your math is wrong, I think.

JP Moresmau
  • 7,388
  • 17
  • 31
0

To over come such defects or error use BigInteger as it has large range and to get precise value.

Bhargav Modi
  • 2,605
  • 3
  • 29
  • 49