在没有特定运算符(+、-、/、*、%、+= %= 等)的情况下获取范围内的可整除数字
Get divisible numbers in a range without certain operators (+, -, /, *, %, += %=, etc)
查找输入范围内可被 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
如果允许使用 == 运算符进行赋值,您可以使用
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;
}
[编辑:已更正代码中的拼写错误]
思考基础数学:
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;
}
查找输入范围内可被 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
如果允许使用 == 运算符进行赋值,您可以使用
int remainder = 0; // assumes we always count up from 1 to n, we will increment before test
在循环内用
替换现有的 ifremainder++;
if (remainder == 3) {
Console.Write(string.Format("{0} ", count));
remainder = 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;
}