首页 > 解决方案 > 在没有特定运算符(+、-、/、*、%、+= %= 等)的范围内获取可整除的数字

问题描述

查找输入范围内可被 3 整除的数字。只能使用 =、++、- 运算符。

我尝试使用移位运算符和其他循环来获取余数,但我总是需要 -= 或类似的东西。

        Console.Clear();
        int n,
            d,
            count = 1;

        // get the ending number
        n = getNumber();

        // get the divisor
        d = 3;// getDivisor();

        Console.WriteLine();
        Console.WriteLine(String.Format("Below are all the numbers that are evenly divisible by {0} from 1 up to {1}", d, n));
        Console.WriteLine();

        // loop through
        while (count <= n)
        {
            // if no remainder then write number
            if(count % d == 0)
                Console.Write(string.Format("{0} ", count));

            count++;
        }

        Console.WriteLine();
        Console.WriteLine();
        Console.Write("Press any key to try again. Press escape to cancel");

预期成绩:

输入结束数字:15

下面是从 1 到 15 能被 3 整除的所有数字

3、6、9、12、15

标签: c#divisionmod

解决方案


想想底层的数学:

2 x 3 = 3 + 3
3 x 3 = 3 + 3 + 3
4 * 3 = 3 + 3 + 3 + 3

...等等。

此外,能被 3 整除意味着乘以 3 的数字必须是偶数......所以......

public bool EvenlyDivisibleBy3(int aNumber)
{
    int even = 2;
    int currentMultiple = 0;
    while (currentMultiple < aNumber)
    {
        int xTimes = 0;
        for (int x = 1; x <= even; x++)
        {
            ((xTimes++)++)++; // add three to xTimes
        }
        currentMultiple = xTimes;
        (even++)++: // next even number
    }

    return currentMultiple == aNumber;
}

推荐阅读