Eslam Hamdy
Eslam Hamdy

Reputation: 7396

How to make a power method without for loops or recursion?

I'm thinking of a method that calculates the power (base 10 only) of an integer which will be passed as an argument but without using for loops or recursion:

here's the method in it's simplest form using forr loop:

 static long power(int val) {
    long y = 10l;

    if (val == 1) {
        return y;
    } else {
        for (int x = 0; x < val - 1; x++) {
            y *= 10;

        }
        return y;

    }
}

Upvotes: 2

Views: 757

Answers (3)

Mark Byers
Mark Byers

Reputation: 838696

The simplest way is to use Math.pow.

Assuming you don't want to do that, you could use a lookup table. There is only a small finite number of results that fit into a long. Something like this would work:

static final long[] results = { 1L, 10L, 100L, /* etc... */ };

static long power(int val) {
    return results[val];
}

Upvotes: 5

charlypu
charlypu

Reputation: 158

There might be a way using Strings. Something like...

String zeros = new String(new char[val]).replace('\0', '0');
String init = "1";
String out = init.concat(zeros);
return Long.valueof(out);

But i think replace will also use a loop inside. Maybe Array.fill doesn't (so you can try with char[])

Upvotes: 0

tiwo
tiwo

Reputation: 3349

I don't see why you would want to do that, but obviously, this would work:

(warning: as ugly as you want it)

  1. convert the number to a string (using base-b representation, b=10)
  2. append zeroes
  3. convert the string to a number and return the result

Of course, this only hides loops

Upvotes: 0

Related Questions