C语言编程:请用1,2,5,7,8,9这六个数字(每个数字至多用一次)来组成一个五位数,使得它能被75整除?
不算不知道,一算吓一跳,竟然有这么多能被75整除的数。
借助全排列函数,末尾是5,其余四位b[4]在a[5]中取,然后判断。
#include "stdafx.h"
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a[5] = { 1,2,7,8,9 },b[4];
while (next_permutation(a, a + 5))
{
for (int i = 0; i < 4; i++)
{
b[i] = a[i];
}
int sum = b[0] * 10000 + b[1] * 1000 + b[2] * 100 + b[3] * 10 + 5;
if (sum % 75 == 0)
cout << b[0] << b[1] << b[2] << b[3] << 5 << endl;
}
system("pause");
return 0;
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> digits{1,2,5,7,8,9};
do{
int result = 0;
for(int i = 0; i < 5; ++i) {
result *= 10;
result += digits[i];
}
if(result % 75 == 0)
cout << result << endl;
} while(next_permutation(digits.begin(), digits.end()));
return 0;
}
#include <stdlib.h>
#include<time.h>
int main(void)
{
int i, j, b,t;
static int a[6] = { 1, 2, 5, 7, 8, 9 };
while (b % 75 != 0)
{
for (i = 0,b=0; i < 5; i++)
b = 10 * b + a[i];
t = a[0];
j = rand() % 6 + 1;
a[0] = a[j];
a[j] = t;
}
printf("b=%d", b);
return 0;
}
5必须被选中,且必须再最后一位
去掉一个数必须和必须能被3整除,所以必须是2或者8
当2被去掉时,最后两位必须是75,所以方法有P(3,3)=6种
当8被去掉时,末尾是75的和25的分别是6种,
所以总共18种可能性
void swap(int *a, int *b)
{
int t = *a;
*a = *b;
*b = t;
}
void permutation(int *nums, int index, int size, int *count)
{
if(index == size)
{
int sum = nums[0]*10000 + nums[1]*1000 + nums[2]*100 + nums[3]*10 + nums[4];
if(sum % 75 == 0)
{
printf("%d ", sum);
*count += 1;
}
}
else
{
for(int j = index; j < size; j++)
{
swap(&nums[j], &nums[index]);
permutation(nums, index+1, size, count);
swap(&nums[j], &nums[index]);
}
}
}
int main()
{ // 1,2,5,7,8,9
int nums1[] = {2,5,7,8,9};
int nums2[] = {1,5,7,8,9};
int nums3[] = {1,2,7,8,9};
int nums4[] = {1,2,5,8,9};
int nums5[] = {1,2,5,7,9};
int nums6[] = {1,2,5,7,8};
int count = 0;
permutation(nums1, 0, sizeof(nums1)/sizeof(int), &count);
permutation(nums2, 0, sizeof(nums2)/sizeof(int), &count);
permutation(nums3, 0, sizeof(nums3)/sizeof(int), &count);
permutation(nums4, 0, sizeof(nums4)/sizeof(int), &count);
permutation(nums5, 0, sizeof(nums5)/sizeof(int), &count);
permutation(nums6, 0, sizeof(nums6)/sizeof(int), &count);
printf("\nTotal count meets requirement is %d\n", count);
getchar();
return 0;
}