Solving hard 3rd-grade math This is a problem proposed by Vietnamese for a 3rd-grade student international contest in Malaysia, 2017. You have to find 3 numbers with conditions:

[][][][] - [][][][] - [] = 2017.

Each digit in each cell range from 1 to 9 and they must be different each other.

I can't solve by hand, so I have made a program to find results.  My code works but is too long, so does anyone have a shorter way?

public class Third_gradeProblem {
public static void main(String[] args) {
int a,b,c,d,e,f,g,h,i;
int so1,so2,so3;
for(a=1;a&lt;=9;a++) {
    for(b=1;b&lt;=9;b++) {
        for(c=1;c&lt;=9;c++) {
            for(d=1;d&lt;=9;d++) {
                for(e=1;e&lt;=9;e++) {
                    for(f=1;f&lt;=9;f++) {
                        for(g=1;g&lt;=9;g++) {
                            for(h=1;h&lt;=9;h++) {
                                for(i=1;i&lt;=9;i++) {
                                    so1=a*1000+b*100+c*10+d;
                                    so2=e*1000+f*100+g*10+h;
                                    so3=i;
                                    if((so1-so2-so3==2017)&amp;&amp;(a!=b)&amp;&amp;(a!=c)&amp;&amp;
(a!=d)&amp;&amp;(a!=e)&amp;&amp;(a!=f)&amp;&amp;(a!=g)&amp;&amp;(a!=h)&amp;&amp;(a!=i)&amp;&amp;(b!=c)&amp;&amp;(b!=d)&amp;&amp;(b!=e)&amp;&amp;
(b!=f)&amp;&amp;(b!=g)&amp;&amp;(b!=h)&amp;&amp;(b!=i)&amp;&amp;(c!=d)&amp;&amp;(c!=e)&amp;&amp;(c!=f)&amp;&amp;(c!=g)&amp;&amp;(c!=h)&amp;&amp;
(c!=i)&amp;&amp;(d!=e)&amp;&amp;(d!=f)&amp;&amp;(d!=g)&amp;&amp;(d!=h)&amp;&amp;(d!=i)&amp;&amp;(e!=f)&amp;&amp;(e!=g)&amp;&amp;(e!=h)&amp;&amp;
(e!=i)&amp;&amp;(f!=g)&amp;&amp;(f!=h)&amp;&amp;(f!=i)&amp;&amp;(g!=h)&amp;&amp;(g!=i)&amp;&amp;(h!=i)) {
                                        System.out.println(so1+" "+so2+" 
"+so3);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

}
}

}


Results:



4613 2587 9;
4613 2589 7;
7412 5386 9;
7412 5389 6;
7421 5396 8;
7421 5398 6;
The main performance problem of your code is that you check for duplicate digits only in the innermost loop, although a collision between e.g. a and b can be detected already in the second loop.

This way you generate 387420489 digit combinations and throw away 99.9% of them (it's only 362880 permutations of 9 digits). Moving the duplicates checks to the outermost place possible can potentially speed up your program by a factor of 1000.

And there might be better algorithms, but on Code Review we concentrate on improving your original code instead of inventing something new.