-2

How to find out whether a number b is can be expressed as a power of another number c and to find the corresponding exponent? Without using math.h or recursion.

The numbers are of the type int!

This is the code I have written:

#include <stdbool.h>


bool is_apowb(int a, int b, int *e) {

int x =0;
if (a>b)
{
    while (a%b==0 && b>0)
    {
        a=a/b;
        x++;
    }

    *e=x;
    return true;
}
else if (a==b)
{
    *e=1;
    return true;
}

else if (b<0)
{
   while (a%b==0)
    {
        a=a/b;
        x++;
    }
    *e=x;

    if (x%2==0)
    {
        return true;
    }
    else return false;
}

return false;

}

The code is failing the following tests:

assert(is_apowb(9,-3,&e));
assert(e == 2);
assert(!is_apowb(8,-2,&e));
assert(e == 2);

Thanks in Advance!

KLMM
  • 93
  • 1
  • 13

2 Answers2

0

If you have a number n and want to know if it is a power of b, you can compute e = log(n)/log(b) and see if it is close to an integer. If so, round e to that integer and compute b^e. If this equals n then you're done and the exponent is e. If not then n isn't a power of b.

You could also divide by b repeatedly in a loop, like so:

e = 0;
while (n%b == 0) {
  n = n/b;
  e++;
}
if (n == 1) return e; // n = b^e
return -1; // n is not a power of b
Charles
  • 11,269
  • 13
  • 67
  • 105
  • no math.h class or recursion – KLMM Feb 20 '15 at 06:17
  • @L887: I used neither in my second answer. The first answer needs logs and powers, and you could either code your own or use math.h. – Charles Feb 20 '15 at 06:18
  • Thanks a lot, I have edited the answer to suit the question. thanks for your reply it was of great help! – KLMM Feb 20 '15 at 06:24
  • I have another question, this code will give us a wrong answer if we input 8 and -2. wheres it gives a right answer for 9 and -3. how do we solve this issue? – KLMM Feb 20 '15 at 20:48
  • @L887: Store whether it's positive or negative, then at the end if it was negative see if the exponent was even or odd and report accordingly. – Charles Feb 20 '15 at 22:17
  • Yeah I tried that please take a look at my edited question. thanks – KLMM Feb 20 '15 at 22:35
  • @L887: You should probably start a new question. – Charles Feb 20 '15 at 22:36
  • No I think its okay, this question is anyway marked as a duplicate. Please take a look at the question and post a separate answer – KLMM Feb 20 '15 at 22:39
0
#include <stdio.h>

int main(int argc, char* argv[] ) {

  int b = atoi(argv[1]);
  int c = atoi(argv[2]);
  int e;

  for (e = 0; b > 1; ++e) {
    if (b%c != 0) break;
    b /= c;
  }

  if (b == 1)
    printf("%d\n", e );
  else
    printf("nope\n");

    return 0;

} // end main()
bgoldst
  • 34,190
  • 6
  • 38
  • 64