Blue Bridge Cup] Real Exam Training 2014 C++A Group Question 3 Magical Formula

Magic formula

 

A multiplication formula composed of 4 different numbers, their product is still composed of these 4 numbers.

such as:

210 x 6 = 1260 
8 x 473 = 3784
27 x 81 = 2187 
meet the requirements.

If the equations satisfying the commutative law of multiplication are counted as the same situation, then, including the three situations listed above, how many kinds of equations are there to meet the requirements?

Please fill in the number, submit the answer through the browser, and do not fill in extra content (for example: list all the calculations).

Answer: 12

 

Problem analysis

This problem has also encountered a similar problem before. The solution can be a violent enumeration, and the method is similar, enumerating all satisfied formulas. It should be noted that the situation here can be three digits * two digits, or two digits multiplied by two digits, so if you enumerate directly, there will definitely be duplicate formulas. So you need to judge! ! !

Judge the two-digit * two-digit formula to ensure that two two-digit numbers cannot be repeated. The method is to either the front number is less than the back number, or the back number is less than the front number, you can choose one of the two.

#include <iostream>
#include <unordered_set>
#include <string.h>
#include <sstream> 
#include <algorithm>
using namespace std;

int ans=0;

bool check(int res, int x){
	stringstream ss;
	string str_res, str_x;
	ss << res;
	ss >> str_res;
	
	stringstream ss1;	//重新申请ss,注意 ! 
	ss1 << x;
	ss1 >> str_x;
	
	sort(str_res.begin(), str_res.end());
	sort(str_x.begin(), str_x.end());
	
	if (str_res == str_x){
		return true;
	} else{
		return false;
	}
	
}
int main(int argc, char** argv) {
	
	for(int i = 1; i < 10; i++){
		for(int j = 0; j < 10; j++){
			if(i != j){
				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){
								int res = i*1000 + j*100 + k*10 + l;
								
								int r1 = i*(j*100 + k*10 + l);	//三位数*一位数 
								if(check(res, r1)){
									ans ++;
								}	
									
								int r2 = (i*10+j) * (k*10+l);	//两位数*两位数 
								if( (i*10+j) < (k*10+l) && check(res, r2)){	
								//注意对两个两位数的大小进行判断,(i*10+j) < (k*10+l),不然会重复 
									ans++;
								}

							}
						}
					}
				}
			}
		} 
	} 
	cout << ans << endl;
	return 0;
}

 

Guess you like

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