大家讲道理2017-04-18 10:55:25
This. . . I don’t know how to put it. . .
Suppose there are n people in total, three people in a row, five people in a row, and seven people in a row. See if there are a, b, c people left in the last row
Isn’t it
n % 3 = a
n % 5 = b
n % 7 = c
Isn’t the following very simple?
Method 1: Brute Force
n Try everything from 10 to 100. I don’t need to say this anymore
Method 2: Mathematical method (Solving Congruence Expressions - Elementary Mathematics)
Example:
n % 3 = 2
n % 5 = 4
What can it be converted into?
设 n / 3 = x 余 2, n / 5 = y 余 4
==> 3x + 2 = 5y + 4
==> 3x = 5y + 2
x,y 在 自然数的最小解是 x = 4, y = 2
==> n 最小是 12
3 和 5 的最小公倍数 = 15
所以 n % 15 == 12
If there are three, count two first, then the third.
天蓬老师2017-04-18 10:55:25
#include <stdio.h>
#include <stdlib.h>
int met(int count, int pision, int remain) {
return count % pision == remain;
}
int getMin(int i, int j, int k) {
if (i == j && j == k) return -1;
if (i >= 3) i %= 3;
if (j >= 5) j %= 5;
if (k >= 7) k %= 7;
int count = 0;
while(1) {
if (count > 10) {
if (met(count, 3, i) && met(count, 5, j) && met(count, 7, k)) {
break;
}
}
count++;
if (count > 100) {
count = -1;
break;
}
}
return count;
}
int main(int argc, char **args) {
if (argc < 4) {
printf("no enough params.");
} else {
int i = atoi(args[1]);
int j = atoi(args[2]);
int k = atoi(args[3]);
int c = getMin(i, j, k);
if (c == -1) {
printf("no qualified number!");
} else {
printf("count = %d", c);
}
}
}