如何透過 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

更新於: 27-8-2021

295 瀏覽

提升你的事業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.