Posts

Showing posts from January, 2011

power(base,n) recursively in java

Given base and n that are both 1 or more, compute recursively (no loops) the value of base to the n power, so powerN(3, 2) is 9 (3 squared). powerN(3, 1) → 3 powerN(3, 2) → 9 powerN(3, 3) → 27 ------------------========================================== public int powerN(int base, int n) { int result=base; if(n==0) return 1; if(n > 0){ return result * (powerN(base,n-1)); } return result; }

fibonocci number in java

The fibonacci sequence is a famous bit of mathematics, and it happens to have a recursive definition. The first two values in the sequence are 0 and 1 (essentially 2 base cases). Each subsequent value is the sum of the previous two values, so the whole sequence is: 0, 1, 1, 2, 3, 5, 8, 13, 21 and so on. Define a recursive fibonacci(n) method that returns the nth fibonacci number, with n=0 representing the start of the sequence. fibonacci(0) → 0 fibonacci(1) → 1 fibonacci(2) → 1 public int fibonacci(int n) { if(n==0) return 0; else if (n == 1) return 1; else if (n == 2) return 1; else return fibonacci(n-1) + fibonacci(n-2); }

BunnyEars--Java Number sequencing problem

We have bunnies standing in a line, numbered 1, 2, ... The odd bunnies (1, 3, ..) have the normal 2 ears. The even bunnies (2, 4, ..) we'll say have 3 ears, because they each have a raised foot. Recursively return the number of "ears" in the bunny line 1, 2, ... n (without loops or multiplication). bunnyEars2(0) → 0 bunnyEars2(1) → 2 bunnyEars2(2) → 5 ---------------------------------------- public int bunnyEars2(int bunnies) { if(bunnies==0) return 0; else if(bunnies%2==0) return 3 + bunnyEars2(bunnies-1); else return 2+bunnyEars2(bunnies-1); }

Sum of Digits in an Integer

Given a non-negative int n, return the sum of its digits recursively (no loops). Note that mod (%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/) by 10 removes the rightmost digit (126 / 10 is 12). sumDigits(126) → 9 sumDigits(49) → 13 sumDigits(12) → 3 ---------------------------------------------------------- public int sumDigits(int n) { int Count=0; if(n/10<10){ Count=(n%10)+(n/10); } else{ Count=sumDigits(n/10)+sumDigits(n%10); } return Count; }

Occurance of a digit in an Integer recursively

Given a non-negative int n, return the count of the occurrences of 7 as a digit, so for example 717 yields 2. (no loops). Note that mod (%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/) by 10 removes the rightmost digit (126 / 10 is 12). count7(717) → 2 count7(7) → 1 count7(123) → 0   --------------------------------- public int count7(int n) { int count=0; int rtemp=0; int ltemp=0; if(n/10<10 ){ rtemp=n%10; ltemp=n/10; if(ltemp==7) count=count+1; if(rtemp==7) count=count+1; } else{ rtemp=n%10; ltemp=n/10; count=count+count7(ltemp); if(rtemp==7) count=count+1; } return count; }