V
V
Vitaly Kolesnik2017-09-07 23:24:11
C++ / C#
Vitaly Kolesnik, 2017-09-07 23:24:11

(C++) How to raise an integer to a non-negative integer power?

There is a problem that I can not solve, tell me what I did wrong and how to write it correctly.
Here is the task itself:
Write a power function that implements the raising of an integer to a non-negative integer power. The power function must take two integers as input and return an integer (see code template). When completing the task, please note that the function must be called power, the function must not read anything from the input or output.
Implementation Requirements: In this assignment, you only need to implement the power. You can define helper functions if you need them. You don't need to implement the main functions.
Restrictions: The cmath library (and math.h) is not allowed.
Code template:
int power(int x, unsigned p) {
int answer;
/* count answer */
return answer;
}
Here is my solution:
int power(int x, unsigned p) {
int answer = 1;
for(int i=1; i <= 2 * p; i++)
{ if(p < 0)
break;
answer *= x;
}
return answer;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
devalone, 2017-09-07
@snapthelife

int power(int x, size_t p) {
  int answer = 1;
  for(size_t i = 0; i < p; i++)
    answer *= x;
  
  return answer;
}

R
Rsa97, 2017-09-08
@Rsa97

int power(int x, unsigned int p) {
  int answer = 1;
  while (p) {
    if (p & 1) {
      answer *= x;
    }
    p >>= 1;
    x *= x;
  }
  return answer;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question