使用模数计算

5 c algorithm operators modular-arithmetic

我正在解决一个问题:用户输入3个树高和树高限制.然后程序计算要删除的树的数量.

样本输入:

 Tree1: 14
 Tree2: 7
 Tree3: 16

 Tree limit: 11
Run Code Online (Sandbox Code Playgroud)

样本输出:

 Amount to remove: 8
Run Code Online (Sandbox Code Playgroud)

这对我来说通常不会太糟糕,虽然我还是初学者,但问题是,我将在没有if语句的情况下计算它.我必须使用Modulus来计算.我花了很长时间研究和尝试不同的东西,但我似乎无法得到它?有任何想法吗?

abe*_*nky 5

您正在寻找的表达方式是:

tree[i] % max % tree[i];
Run Code Online (Sandbox Code Playgroud)

tree[i]大于max:
例如:16和11

16 % 11 = 5
5 % 16 = 5
Run Code Online (Sandbox Code Playgroud)

但是当tree[i]小于max:
例如:7和11

7 % 11 = 7
7 % 7 = 0
Run Code Online (Sandbox Code Playgroud)

int main(void)
{
    int tree[3] = {0};
    int max = 0;
    int cut = 0;

    printf("Max Height: "),
    scanf("%d", &max);

    for(int i=0; i<3; ++i)
    {
        printf("Tree%d: ",i+1),
        scanf("%d", &tree[i]);
    }

    for(int i=0; i<3; ++i)
    {
        cut += (tree[i] % max) % tree[i];
    }
    printf("Amount to remove: %d\n", cut);

    getchar();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在2015年8月(距离原始帖子近2年),我决定重新审视这个问题,并提出一个通用的解决方案.

它看起来有点工作,但完整的表达是:

int cut = (tree % max % tree) + !!(tree/max) * (tree/max - 1) * max;
Run Code Online (Sandbox Code Playgroud)

例子:

| Tree | Max | Expression      | Answer |
|    4 |  11 | 0 + 0 * -1 * 11 |      0 |
|   47 |  11 | 3 + 1 * 3 * 11  |     36 |
Run Code Online (Sandbox Code Playgroud)

注意:我用!! (double-not)几乎只是一个C/C++构造.可能无法使用其他语言.

  • 如果`tree [i]`比如25,这会有用吗?你可以从模数计算中得到3的答案. (4认同)
  • +1,可能会处理OP的情况,但遗憾的是这只能持续到`tree [i]> = n*max`,其中`n> 1`.答案将包括整数除法*和*modulo,但这会将OP放在最近的轨道上. (3认同)

Dig*_*uma 5

这是一般解决方案:

#include <stdio.h>

#define CUTAMOUNT(tr, lim) (tr - lim) * (((2 * tr) - ((2 * tr) % (tr + lim))) / (tr + lim - 1))

int main (int argc, char **argv) {

    int tree1 = 14;
    int tree2 = 7;
    int tree3 = 16;
    int limit = 11;

    int cutamounttotal = 0;

    cutamounttotal += CUTAMOUNT(tree1, limit);
    cutamounttotal += CUTAMOUNT(tree2, limit);
    cutamounttotal += CUTAMOUNT(tree3, limit);

    printf("Amount to remove: %d\n", cutamounttotal);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)
  • 没有分支
  • 没有循环
  • 没有条件
  • 没有三元运作
  • 没有按位操作
  • 没有逻辑运算

只有算术运算.诀窍是要理解%是唯一可以创建步骤的算术运算符.操作数必须适当调整大小,以确保步骤只发生在我们想要的地方,而不是其他地方.然后我们可以利用该步骤来提供所需的结果.

  • 无瑕!我们说话的时候很高兴吃我的话. (2认同)