Pergunta de entrevista da empresa Microsoft

How can you write a recursive function calculating the exponential of a number?

Respostas da entrevista

Sigiloso

19 de mar. de 2012

//Imports using System; //Test class class Test { //Constructor public Test() { //Nothing } public int RecursiveExp(int x, int n) { //First base case if (n == 0) { return 1; } //Second base case if (n == 1) { return x; } //Even values of (n) if (n % 2 == 0) { int y = RecursiveExp(x, n / 2); return y * y; } //Odd values of (n) else { int y = RecursiveExp(x, n - 1); return x * y; } } } //Main class class Program { //Main static void Main(string[] args) { //Create a test object Test tst = new Test(); //Examples Console.Out.WriteLine(tst.RecursiveExp(2, 0)); Console.Out.WriteLine(tst.RecursiveExp(2, 1)); Console.Out.WriteLine(tst.RecursiveExp(2, 3)); Console.Out.WriteLine(tst.RecursiveExp(2, 4)); } }

2

Sigiloso

16 de fev. de 2012

f(n) = a if n=0. f(n) = a*f(n-1) otherwise.