Search code examples
calgorithmoperatorsmodular-arithmetic

Calculating using modulus


I am working on a problem: The user enters 3 tree heights and also the tree height limit. The program then calculates the amount of tree to remove.

Sample input:

 Tree1: 14
 Tree2: 7
 Tree3: 16

 Tree limit: 11

Sample output:

 Amount to remove: 8

This would usually not be too bad for me although I am still a beginner but the problem is, I am going to be calculating it WITHOUT an if statement. I must use Modulus to calculate. I have spent a very long time researching and trying different things but I just cannot seem to get it? Any ideas?


Solution

  • The expression you're looking for is:

    tree[i] % max % tree[i];
    

    When tree[i] is greater than max:
    example: 16 and 11

    16 % 11 = 5
    5 % 16 = 5
    

    But when tree[i] is less than max:
    example: 7 and 11

    7 % 11 = 7
    7 % 7 = 0
    

    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;
    }
    

    In August 2015 (nearly 2 years from the original post), I decided to revisit this question, and come up with a generalized solution.

    It look a little work, but the full expression is:

    int cut = (tree % max % tree) + !!(tree/max) * (tree/max - 1) * max;
    

    Examples:

    | Tree | Max | Expression      | Answer |
    |    4 |  11 | 0 + 0 * -1 * 11 |      0 |
    |   47 |  11 | 3 + 1 * 3 * 11  |     36 |
    

    Note: My use of !! (double-not) is pretty much a C / C++ only construct. May not work in other languages.