1, the problem description
① Huai'an folklore with a story - " Han Xin Troops", followed by a phrase "Han soldiers, the more the better ."
② a thousand years ago, " Sun Tzu Suan Jing ", there is such an arithmetic problem: "Today there was an unknown number, the number of remaining two hundred thirty-three, fifty-five number of remaining three numbers of the remaining two hundred seventy-seven, geometric asked was "in accordance with today's words:? a number is divided by 32, is divided by 53, divided by more than 72, find the number. This problem was also known as "Han soldiers." It forms a class of problems, that is, elementary number theory solutions of the congruence.
③ problem: a number is divided by 32, is divided by 53, is divided by 72, to find the minimum number of matches.
2, concluding ideas
1 idea: [violent solving method - low traversal, efficiency]
From 0 up to a large value is calculated to be judged
public static int dealSingle1(int index0,int index1,int index2){//暴力求解 boolean a,b,c; for(int i=0;i<Integer.MAX_VALUE;i++){ a=(i%3==index0); b=(i%5==index1); c=(i%7==index2); if(a&&b&&c){ return i; } } return -1; }
2 thoughts: [the use of mathematical knowledge by calculating a further optimization, it should be the fastest]
Listed first number is divided by 32: 2,5,8,11,14,17,20,23,26 ......
public static int dealSingle2(int index0,int index1,int index2) {//2,数学方法求解 long startTime = System.currentTimeMillis(); int num=0,num1=0; for(int i=0;i<Integer.MAX_VALUE;i++){ num=3*i+index0; if(num%5==index1){ break; } } for(int i=0;i<Integer.MAX_VALUE/15;i++){ num1+ 15 * NUM = I; IF (num1% ==. 7 index2) { Long endTime = System.currentTimeMillis (); System.out.println ( "Method 2: mathematical optimization, Processed:" + (endTime- the startTime)) ; return num1; } } return -1 ; }
3 ideas: [dominated by the large numbers numerical computation, very fast]
public static int dealSingle3(int index0,int index1,int index2){//处理单个数据 long startTime = System.currentTimeMillis(); int num=-1; boolean a,b; for(int i=0;i<Integer.MAX_VALUE/7;i++){ num=i*7+index2; a=(num%3==index0); b=(num%5==index1); if(a&&b){ long endTime = System.currentTimeMillis (); System.out.println ( "Method 3: mathematical optimization, Processed:" + (endTime- the startTime)); return NUM; } } return NUM; }
3, the problem extended
All calculated results of [3,5,7 Han soldiers all prime numbers, then 0 ~ (3 * 5 * 7-1) all data within this range is a situation in which]
public static int [] [] [] dealAll () { // each calculation only once, until all data int [] [] [] = ARR new new int [. 3] [. 5] [. 7 ]; for ( int I = 0; I <(. 5 * *. 7. 3); I ++ ) { ARR [I %. 3] [I. 5%] [% I. 7] = I; } return ARR; }