[Blue Bridge Cup] Exam Training 2013 C++A Group Question 2 Excluding Square Number

Exclusive square 

Title:
Excluding Square Number Xiao Ming is staring at the number 203879 in a daze.
It turns out, 203879 * 203879 = 41566646641.
What is the magic? Observe carefully, 203879
is a 6-digit number, and the number on each digit of it is different, and all the digits after it squared do not appear to form it. Own figures.
There is another 6-digit number with such characteristics. Please find it!

Answer: 639172

Problem analysis

Violent enumeration

The violent enumeration method respectively cyclically composes the six digits. According to the conditions, each digit of the six digits is different, and the number obtained by the final square does not contain its own number, then check this condition.

It should be noted that the number obtained by multiplying two six-digit numbers is very large, exceeding the range of int, so it is best to use long long large numbers to store them to avoid errors. In the future, you will encounter similar problems with large numbers. It is safer to use long long. This is also a judgment on the range of values.

A useful function is used here to convert an integer to a string

#include <iostream>
#include <sstream>
using namespace std;

//t2:排它平方数 

//整数转成字符串 
void i2s(long long x, string &basic_string){
	stringstream ss;
	ss << x;
	ss >> basic_string; 
}
 
//判断xx是否包含x中的数字 
bool check(long long x, long long xx){
	string s_x, s_xx;
	i2s(x, s_x);
	i2s(xx, s_xx);
	
	for(int i = 0; i < s_x.length(); i++){
		if(s_xx.find(s_x[i]) != string::npos){
			return false;
		}
	}
	return true; 
}

int main(int argc, char** argv) {
	for(int i = 1; i < 10; i++){
		for(int j = 0; j < 10; j ++){
			if(j != i){
				for(int k = 0; k < 10; k++){
					if(k != i && k != j){
						for(int l = 0; l < 10; l ++){
							if(l != i && l != j && l != k){
								for(int h = 0; h < 10; h ++){
									if( h != i && h != j && h != k && h != l){
									for(int m = 0; m < 10; m ++){
										if( m != h && m != i && m != j && m != k && m != l){
											long long num = i*100000 + j*10000 + k*1000 + l*100 + h*10 + m;
											if(check(num, num*num)){
												cout << num << " " << num*num << endl;:
											}
										}
									} 
								}
							}
						}}
					}
				}
			}
		}
	} 
	
	return 0;
}

 

In this question, although it is still a violent solution, it is impossible to directly solve it. Then it takes advantage of computer calculations. For this kind of problem, clarify your goal and write it step by step according to the idea. The code is not difficult. If it is too high, you can always get results.

Guess you like

Origin blog.csdn.net/weixin_44566432/article/details/115086587