简体   繁体   中英

How can I find all the three-digit numbers that each digit is in 3 and the addition of the digits is equal to the number itself

How can I find all the three-digit numbers that each digit is in 3 and the addition of the digits is equal to the number itself.

for example:

3 ^ 3 + 7 ^ 3 + 1 ^ 3 = 371

Update

I have to find all the numbers from 100-999 and then, separate each digit and then perform a three-digit operation (mathematical operation) and check whether all digits are equal to the number itself

The number 371 fulfills the following condition: the sum of its digits in the third is equal to the number itself

Answer

You could use something like this

public static IEnumerable<int> GetDigits(int num)
{
   do { yield return num % 10; } while ((num /= 10) > 0);
}

public static bool SomeWeirdMathsOp(int num)
{
   return num == GetDigits(num).Sum(x => (int)Math.Pow(x, 3));
}

Usage

var list = Enumerable.Range(100, 900).Where(SomeWeirdMathsOp);
foreach (var item in list)
    Console.WriteLine(item);

Output

153
370
371
407

Full demo here


Benchmarks

Just for fun (and because i'm annoying) i decided to benchmark everyone's answers

Results

Mode            : Release
Test Framework  : .NET Framework 4.7.1
Benchmarks runs : 100 times (averaged/scale)

Scale : 900
Name      |     Time |    Range | StdDev |    Cycles | Pass
--------------------------------------------------------------
MineTimes | 0.136 ms | 0.016 ms |   0.03 |   456,359 | Yes
Mine      | 0.250 ms | 0.005 ms |   0.05 |   830,104 | Base
Mahsa     | 0.332 ms | 0.008 ms |   0.03 | 1,122,867 | Yes
JohnyL    | 2.135 ms | 0.204 ms |   0.34 | 7,262,956 | Yes

MineTimes is Enigmativity's version which just does the power manually

public static bool SomeWeirdMathsOp(int num)
{
   return num == GetDigits(num).Sum(x => x * x * x);
}

Additional Resources

yield (C# Reference)

When you use the yield keyword in a statement, you indicate that the method, operator, or get accessor in which it appears is an iterator. Using yield to define an iterator removes the need for an explicit extra class (the class that holds the state for an enumeration,

% Operator (C# Reference)

The remainder operator (%) computes the remainder after dividing its first operand by its second. All numeric types have predefined remainder operators.

Enumerable.Sum Method (IEnumerable, Func)

Computes the sum of the sequence of Double values that are obtained by invoking a transform function on each element of the input sequence.

Math.Pow Method (Double, Double)

Returns a specified number raised to the specified power.

Enumerable.Range Method (Int32, Int32)

Generates a sequence of integral numbers within a specified range.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM