如何通过使用 C# 回溯找到任何给定数字的幂?
创建一个函数来查找幂,它接受数字x和n,其中x是2,n是多少次,我们必须做幂。如果数字是偶数,那么我们必须做x*x,如果数字是奇数,则将结果与x*x相乘。继续递归调用,直到n变为0。
假设如果我们有一个数字2和8,那么2*2*2*2*2*2*2*2=256。
示例
using System;
namespace ConsoleApplication{
public class BackTracking{
public int FindPower(int x, int n){
int result;
if (n == 0){
return 1;
}
result = FindPower(x, n / 2);
if (n % 2 == 0){
return result * result;
}
else{
return x * result * result;
}
}
}
class Program{
static void Main(string[] args){
BackTracking b = new BackTracking();
int res = b.FindPower(2, 8);
Console.WriteLine(res);
}
}
}输出结果256
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短