This one's a strange question.
But first, a little bit of context, a math problem that a teacher asked:
In a given range, how many 4 digit numbers are there, where the 'thousands' digit is equal to the sum of the other 3 digits?
I wrote a quick (to write, not to run) brute-force algorithm that simply iterates through the all the values in a given range.
From here, I have two problems.
Here's the first algorithm I wrote: (ignore syntax errors please, I'm writing this outside of an IDE)
public class Test
{
public static void Main()
{
int UpperBoundInput = 1234; //Input 4 digit upper bound here.
string LowerBoundInput = 0000; //Input 4 digit bound here.
int TrueCount = 0;
int(int CurrentCount = LowerboundInput; CurrentCount < UpperBoundInput; CurrentCount++)
{
string CurrentCountString = CurrentCount.tostring();
if(CurrentCountString[0] = (CurrentCountString[1] + CurrentCountString[2] + CurrentCountString[3]))
{
TrueCount++;
}
}
}
This code can be found here.
The problem here is that having 4 digit numbers leads to all sorts of problems with zeroes (0001 == 1), out of range errors.
I tried a different algorithm (for the sake of length, I'll only describe it), which is 4 nested for loops which iterates through the thousands, tens ect ect and does the same comparason.
This algorithm works, but it's incredibly innefficent.
~~~
Can anyone write a nicer looking algorithm to brute force this problem?
I know there's a mathematical algorithm that could be used, posting that would be awesome too.