
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to find the power of any given number by backtracking using C#?
Create a function to Find Power which takes the number x and n, where x is the 2 and n is how many times, we have to do the power. If the number is even then we have to do x*x and if the number is odd multiply the result with x*x. Continue the recursive call until the n becomes 0.
Suppose if we have a number 2 and 8, then 2*2*2*2*2*2*2*2 =256.
Example
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); } } }
Output
256
Advertisements