find out minimum numbers from fibonacci series required such that sum of numbers should be equal to a given Number N?
Note : repetition of number is allowed.
Example1.
N= 7;
answer = 2 (5 + 2 = 7)
Example 2.
N = 70;
Answer = 3 (34 + 34 + 2)
implementation code:
import java.util.Stack;
public class HelloWorld{
static Stack st = new Stack();
public static void main(String []args){
fibonacciSum(123);
}
// put fibonacci series number into stack till number was greater than N,and then recsum
public static void fibonacciSum(int n){
int prev = 1, cur = 2;
st.push(prev);
while(cur<n){
int temp = prev;
prev = cur;
cur = temp + prev;
st.push(prev);
}
int sum = (int)st.pop();
System.out.println(sum);
recSum(sum,n);
}
// check the sum + the top number of stack is equal to N or not,if true,printf
// if greater,remove the top number and then call recsum
// if less ,sum add the top number of stack,and stack remove it ,and then call recsum
public static void recSum(int sum, int n){
if((sum+(int)st.peek())==n){
System.out.println(sum+(int)st.peek() + " - " + st.pop());
}
else if((sum+(int)st.peek())>n){
st.pop();
recSum(sum, n);
}
else if((sum+(int)st.peek())<n){
sum+=(int)st.peek();
System.out.println(sum + " - " + st.peek());
recSum(sum,n);
}
}
A number is called as a stepping number if the adjacent digits are having a difference of 1. For eg.8,343,545 are
stepping numbers. While 890, 098 are not. The difference between a ‘9’ and ‘0’ should not be considered as 1
stepping number==相邻位数的值相差1或者个位数,for example: 123,121,1232,1234
implementation code:
Here is small example:
s = 10 , e = 1000
length = 2
1 (base) -> for 1 next digit can be 0 or 2 - >10 and 12 (they are stepping, length == 2 reached)
2 (base) -> for 2 next digit can be 1 or 3 - > 21 and 23
...
9 (base) -> for 9 the only variant is 8 - > 98
length = 3
1(base) -> 10 -> 101 -> 1010 and 1012
12 -> 121 and 123
2(base) -> 21 -> 210 and 212
23 -> 232 and 234
static void Dfs(long s, long e , long length , long num) {
//actually,the length was used to indicate the digit ,according number(length==n-1)to generate number(length==n)
// length==0说明已经判断到最后一位,可以打印了 if (length-1 == 0) { if ( s <= num && num <=e) Console.WriteLine(num); return; }
// take last digit of num and find all possible wariants for the next one.
// For 0 the only possible wariant is 1 , for 9 it's 8, for others - (other-1) and (other +1) var lastDigit = num%10; if (lastDigit == 0) { Dfs(s , e,length-1 , num*10+1); } else if (lastDigit == 9) { Dfs(s, e, length - 1, num*10 + 8); } else { Dfs(s , e,length-1 , num*10+lastDigit-1); Dfs(s , e,length-1 , num*10+lastDigit+1); } } static void Main(string[] args) { long s = 1; long e = 1000000000000000; var sLength = (int)Math.Floor(Math.Log10(s) + 1); var eLength = (int)Math.Floor(Math.Log10(e) + 1); for (long i = sLength; i <= eLength; ++i) { //no leading zero for (long j = 1; j < 10; ++j) { Dfs(s , e, i , j); } } }