Home > Mobile >  How to get sum of the cubes of its digits
How to get sum of the cubes of its digits

Time:08-26

First of all I want to know what it is even called; lets take an example a number

153

now let's cube all its digits:

(1 * 1 * 1)   (5 * 5 * 5)   (3 * 3 * 3) == 153

if the output is 153, what exactly is this thing called. I hope you understand what I'm trying to say now. I also want to implement the same thing in code without using any predefined methods in C#

How can I do that?

Please note that the input number can be dynamic and not hard coded like 153 as example

CodePudding user response:

First of all, please note that the sequence is finite: if we have 5 digits number, the maximum sum of digits cubed can be

99999 -> 5 * 9**3 == 3645 < 10000

Using calculus you can prove that sum of digits cubed grows slower than number itself (let me omit the proof); so if number has 5 or more digits it can't be the number we are looking for.

So far so good, we should check numbers from 1 to 10000 only.

Code: (please, fiddle yourself)

private static IEnumerable<int> A046197() {
  for (int number = 1; number < 10000;   number) {
    int s = 0;
        
    for (int n = number; n > 0; n /= 10) {
      int d = n % 10;

      s  = d * d * d;
    }

    if (number == s)
      yield return number;
  }
}

Let's have a look:

Console.Write(string.Join(", ", A046197()));

Output:

1, 153, 370, 371, 407

Note, that these numbers are A046197 sequence in oeis where you can find details.

  • Related