获取没有特定运算符的范围内的可除数(+,-,/,*,%,+ =%=等)

时间:2019-02-03 17:15:22

标签: c# division mod

在输入范围内找到可被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,9,12,15

2 个答案:

答案 0 :(得分:0)

如果允许==运算符进行赋值,您可以输入类似

int remainder = 0; // assumes we always count up from 1 to n, we will increment before test

在循环内部,将现有的if替换为

remainder++;
if (remainder == 3) { 
     Console.Write(string.Format("{0} ", count));
     remainder = 0;
}

[编辑:代码中的错字已更正]

答案 1 :(得分:0)

考虑基础数学:

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