寻找符合规定的数
任意给定一个自然数N,寻找一个M,要求M是N的倍数,且它的所有位数都是0或1组成并要求M尽量小。
例:N=3 M=3*37=111
N=31 M=31*3581=111011
#include <stdio.h> /* This function is used to add 1 to binary number of n. num[0] is high bit, * num[8] is low bit*/ void b_add(int num[]) { int i = 8; while (++num[i] == 2) { num[i] = 0; i--; } } /* This function is used to convert the binary number to decimal number. * exp.num[0] ~ num[5] is 0, num[6] ~ num[8] is 1, then the decimal * number is 111*/ int b_to_d(int num[]) { int d_num, i; for (d_num = 0, i = 0; i < 9; i++) { d_num *= 10; d_num += num[i]; } return d_num; } int main() { int n, m; int binary_num[9]; while (1) { printf("Please input a number or input ctrl + c to quit: \n"); scanf("%d", &n); printf("The number qualified: \n"); int i; for (i = 0; i < 9; i++) //init the binary_num to 000000000 binary_num[i] = 0; do { b_add(binary_num); if ((m = b_to_d(binary_num)) % n == 0) printf("%d\n", m); } while(m < 111111111); } return 0; }
这段代码可以统计九位数字内符合要求的数字,测试如图: