例題7-1 除法

輸入正整數n,按從小到大的順序輸出所有形如abcde / fghij = n的表達式,其中a~j恰好爲數字0~9的一個排列(可以有前導0),2≤n≤79

input:

62

output:

79546 / 01293 = 62

94736 / 01528 = 62


書上示例:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

int main() {
	int n, kase = 0;
	char buf[99];
	while (scanf("%d", &n) == 1 && n)
	{
		int cnt = 0;
		if (kase++) 
			printf("\n");
		for (int fghij = 1234; ; fghij++) 
		{
			int abcde = fghij * n;
			sprintf(buf, "%05d%05d", abcde, fghij);	
			if (strlen(buf) > 10) break;
			sort(buf, buf + 10);
			bool ok = true;
			for (int i = 0; i < 10; i++)
				if (buf[i] != '0' + i) ok = false;
			if (ok) {
				cnt++;
				printf("%05d / %05d = %d\n", abcde, fghij, n);
			}
		}
		if (!cnt) printf("There are no solutions for %d.\n", n);
	}
	return 0;
}


枚舉,題上求除法,算法可用乘法反求結果,避免出現小數。fghij從1234開始(01234),直到abcdefghij的總長>10停止枚舉,中間用排序,方便重複數字的檢測


int sprintf( char *buffer, const char *format, [argument] … );

bufferchar型指針,指向將要寫入的字符串的緩衝區。
format:格式化字符串。
[argument]...:可選參數,可以是任何類型的數據。

%nd 表示輸出的整型寬度至少爲n位,右對齊,%5d即寬度至少爲5位,位數大於5則輸出實際位數
%0nd 表示輸出的整型寬度至少爲n位,不足n位用0填充


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章