My program specifications are as follows. 1. All four digits are different 2. The digit in the thousands place is three times the digit in the tens place 3. The number is odd. 4
I believe this can be simplified significantly by looking at the given inequalities, soemthing like
// thousands + hundreds + tens + ones == 27
// thousands = tens * 3, or tens = thousands / 3
// thousands = 3, 6 or 9
public static void main(String[] args) {
// thousands = tens * 3; so it must be a multiple of 3.
for (int thousands = 3; thousands < 10; thousands += 3) {
for (int hundreds = 0; hundreds < 10; hundreds++) {
if (hundreds == thousands) {
continue;
}
// thousands = tens * 3; so the reverse is also true
int tens = thousands / 3;
if (tens == hundreds) {
continue;
}
// All of the digits sum to 27.
int ones = 27 - thousands - hundreds - tens;
if (ones > 9 || ones % 2 != 0 || ones == tens
|| ones == hundreds || ones == thousands) {
continue;
}
int val = (thousands * 1000) + (hundreds * 100) + (tens * 10)
+ ones;
System.out.println(val);
}
}
}
Of course, the output is still
9738
Swap while(found)
for while(!found)
.
Just think about it logically. You don't want to look while you've found something. You want to keep looking while you've not found it.
boolean found = false;
while (found)
This alone ensures the while loop will never be entered, since found
is false. Anything inside the while loop doesn't make any difference, since it will never be executed.
You probably meant to write
while (!found)
Beside this error, your conditions are over complicated. Here's how you can simplify them :
if ((position0 == (3 * position2)) && // note that position0 is the "thousands place", not position3
((position0+position1+position2+position3) == 27) && // sum of digits
(position3 % 2 == 1) && // odd number
(position0 != position1 && position0 != position2 && position0 != position3 &&
position1 != position2 && position1 != position3 && position2 != position3)) { // different digits
found = true;
}