入门经典-7.1简单枚举,182-uva725除法-排列,sprintf(),生成测试法❤难度:1

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
char buf[99];
int main(){
	int kase=0,n;
	while(cin>>n&&n){
		int cnt=0;
		if(kase++) cout<<endl;
		for(int fghij=1234;;fghij++){//fghij=1234即01234 这里没有按排列顺序枚举 而是采用生成测试法(即从01234到99999每次自增1 ) 更简单 
			int abcde=fghij*n;       //fghij枚举之后 再根据关系式得到abcde 利用sprintf() 合并成一个字符串 再判断是否是一个排列 
			sprintf(buf,"%05d%05d",abcde,fghij);//%05d 0的作用是位数不足则补充0 
			if(strlen(buf)>10) break;//位数超过10 肯定不成立 
			sort(buf,buf+10);
			
			//判断是否为一个排列 
			bool ok=true;
			for(int i=0;i<10;i++){
				if(buf[i]!='0'+i){
					ok=false;
					break;
				}
			}
			if(ok){
				cnt++;
				printf("%05d / %05d = %d\n",abcde,fghij,n);
			}
		}
		if(!cnt) printf("There are no solutions for %d.\n",n);
	}
	return 0;
}
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<set> 
using namespace std;
char buf[99];
int main(){
	int kase=0,n;
	while(cin>>n&&n){
		int cnt=0;
		if(kase++) cout<<endl;
		for(int fghij=1234;;fghij++){//fghij=1234即01234 这里没有按排列顺序枚举 而是采用生成测试法(即从01234到99999每次自增1 ) 更简单 
			int abcde=fghij*n;       //fghij枚举之后 再根据关系式得到abcde 利用sprintf() 合并成一个字符串 再判断是否是一个排列 
			sprintf(buf,"%05d%05d",abcde,fghij);//%05d 0的作用是位数不足则补充0 
			if(strlen(buf)>10) break;//位数超过10 肯定不成立 
			//sort(buf,buf+10);
			
			//判断是否为一个排列 
			bool ok=true;
			set<char> s;//用set判断是否有重复元素 即是否是一个排列 
			s.clear();
			for(int i=0;i<10;i++){
				if(s.count(buf[i])){
					ok=false;
					break;
				}
				else s.insert(buf[i]);
			}
			if(ok){
				cnt++;
				printf("%05d / %05d = %d\n",abcde,fghij,n);
			}
		}
		if(!cnt) printf("There are no solutions for %d.\n",n);
	}
	return 0;
}
第二个代码利用set判重

猜你喜欢

转载自blog.csdn.net/qq_41093189/article/details/79768882