PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 17, 2022

[FIXED] How to get sum of the cubes of its digits

 October 17, 2022     algorithm, c#, cube, integer     No comments   

Issue

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


Solution

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 (max possible sum) < 10000 (min possible number)

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.



Answered By - Dmitry Bychenko
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing