I have sequence of numbers:
0, 1, 1, 2, 3, 5, 8, 13, 12, 7, 10…
Each number then is the sum of the separete digits of the previous elements.
It’s a bit like Fibonacci..
I want to write a function
int FindSimilarFibo(int x)
{
//x = 10 return 10
//x = 6 return 8
}
I wrote this, but I can’t figure out the correct algorithm:
int FindSimilarFibo(int x) {
int p = 0;
int q = 1;
for (int i = 0; i < n; i++)
{
int temp = p;
p = q;
q = temp + q;
if (q > 9)
{
int leftQ = q % 10;
int rightQ = q / 10;
q = leftQ + rightQ;
q = temp + q;
}
if (p > 9)
{
int leftQ = q % 10;
int rightQ = q / 10;
temp = leftQ + rightQ;
p = q;
q = temp + q;
}
}
return p;
}
>Solution :
The problem looks to be that you’re overwriting previous values when computing the digits-sum of the next; so… don’t do that? perhaps:
static int FindSimilarFibo(int n)
{
int p = 0;
int q = 1;
for (int i = 0; i < n; i++)
{
var next = SumDigits(p) + SumDigits(q);
p = q;
q = next;
}
return p;
static int SumDigits(int value)
{
int sum = 0;
while (value > 9)
{
sum += value % 10;
value /= 10;
}
return sum + value;
}
}