Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sum digits of previous numbers algorithm in C#

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;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading