I got a four-digit positive number. I need to square the two digits in middle to generate a new number on which the same procedure is applied. The numbers get saved in a list. This loops as long as there isn't an equal number generated (the list contains the number already). If a number is generated containing less than four digits, the code takes the first and middle digit.
- 1 23 4
- 23² = 529
- 52 9
- 52² = 2704
- 2 70 4
- 70² = ...
I've done the core magic within int current = (int) Math.Pow (number % 1000 / 10, 2);
. Is this the most elegant way to solve this?
ArrayList<int> numbers = new ArrayList<int> ();
public void generateNumbers (int number) {
// just in case :)
if (number > 9999) {
throw new ArgumentOutOfRangeException ("Number must be smaller than 10,000");
}
// Remove the thousands and get the times 10 fits in (you've only the two numbers in the middle left)
int current = (int) Math.Pow (number % 1000 / 10, 2);
// Repeat until an equal number is in the ArrayList
if (numbers.Contains (current)) {
return;
} else {
numbers.Add (current);
this.generateNumbers (current);
}
}
ArrayList<int>
is meant to beList<int>
, yes? \$\endgroup\$