Implement n^k C using recursion

describe:

Write a function to implement n^k, using recursion.

Ideas:

        This problem is relatively easy for students who are skilled in recursion. But it is easy for unskilled students to think confused. We customize the function my_pow to achieve this function. We mainly talk about the part of the recursive function.

        This question can be seen as n*n*n. . . (there are k multiplications of n). Using the characteristics of recursion, we can reduce k by one after each multiplication of n. Here, it is necessary to explain the recursive characteristics and operation mode.

        First, let's explain the three elements of recursion:

                1. The main way of thinking about recursion: make big things small. That is to say, when we think, we only need to think about part of it. For example, to realize n * n * n * n, we think about multiplying the first two. If the code is correct, then the result of the latter multiplication is naturally correct.

                2. Necessary condition for recursion: there is a conditional restriction and each recursion will get closer and closer to this condition . Otherwise, it will cause stack overflow problem. This problem is also the most common mistake of recursion. About what is stack overflow, if you are interested, you can use Baidu.

               3. Recursive thinking and proficiency need to be solved by drawing.

        Speaking of the recursive running steps, many people don't know what the process is like at the beginning, so here I will release some correct codes first, and let's feel the process together by drawing pictures. (It should be noted that: k--; is written separately for the convenience of explanation and understanding (the difference between prefix ++ and suffix ++). A better way to write it should be to remove the k--; line and write it as return n * my_pow( n, --k); If it is written as return n * my_pow(n, k--); what will be the result? (Infinite infinite loop leads to stack overflow))

         The complete code is as follows:

#include<stdio.h>

int my_pow(int n, int k)
{
	if(k > 0)
	{
		k--;
		return n * my_pow(n, k);
	}

	return 1;
}

int main(void)
{
	int n = 0, k = 0;
	scanf("%d %d", &n, &k);
	int ret = my_pow(n, k);
	printf("%d", ret);
	
	return 0;
}

        The results are as follows:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324174540&siteId=291194637