java - C语言算法题-韩信点兵 求解?
高洛峰
高洛峰 2017-04-18 10:53:25
0
2
673


完全不知道怎么下手??

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
大家讲道理

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.

Peter_Zhu
#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);
        }
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!