Java find use for loop abcd four integer satisfying (ab + cd) (ab + cd) = abcd number (Ziph)

@Java

Hello everyone, I'm Ziph!

topic:

(For loop) to find the four integer satisfying abcd (ab + cd) (ab + cd) = abcd number

plan 1:

1 idea:
using common ideas for loop calculation
since it is 4 digits, then 4-digit start is 1000, the end of 9999. This is for the use of digital loop parameters, abcd that is, 1000 (the beginning). So we will need to meet the meaning of the questions, you have to create two variables is ab, cd. ab, cd obtained similarly obtained in respect abcd bits, ten, one hundred bar, after satisfying (ab + cd) (ab + cd) = abcd conditions may print the value of abcd.

public class TestPlan {
	public static void main(String[] args) {
		for (int abcd = 1000; abcd <= 9999; abcd++) {
			int ab = abcd / 100;//类似求个位、十位、百位的案例
			int cd = abcd % 100;//如果还不知道怎么求,可以把ab、cd拆开看就相当于是个位和十位了
			if ((ab + cd) * (ab + cd) == abcd) {//满足条件
				System.out.println(abcd);
			}
		}
	}
}

Scenario 2 (optimized version):

2 ideas:
the use of a perfect square calculation
look casual working the stem, to meet the requirements (ab + cd) (ab + cd) = abcd this condition, the two conditions (ab + cd) multiplied by the whole we can It is defined as a number of variables num, num means that the use of the square to seek abcd. And abcd this number it is called a perfect square. (8 * 8 * 9 = 64,9 = 81 and 64, 81 this number is called a perfect square) then we are now looking for 1000 from the nearest perfect square is what we are familiar with 32 * 32 = 1024,100 * 100 = 10000, we take 99 * 99 99 as a further parameter in the cycle. 32 and the number of computers involved in such judgments only between 99 to 67, compared from 1000-9999 to determine a lot less of it, greatly improving the efficiency of the computer, optimized our code to enhance the force of your grid, not at not kill three birds!

public class TestPlan {
	public static void main(String[] args) {
		for (int num = 32; num <= 99; num++) {
			int abcd = num * num;
			int ab = abcd / 100;
			int cd = abcd % 100;
			if (ab + cd == num) {//因为我们当初把(ab + cd)这个整体看成了num
				System.out.println(abcd);	
			}
		}
	}
}

Implementation of the results: 2025,3025,9801
Here Insert Picture Description
have questions, please leave a message reply!

Bye

Published 10 original articles · won praise 21 · views 3866

Guess you like

Origin blog.csdn.net/weixin_44170221/article/details/104233443