[英]How to run a c program using loops to find the remainder of two numbers without using multiplication, division and modulo operators?
#include <stdio.h>
int main()
{
int num1, num2;
printf ("Input value for num1: ");
scanf ("%d", &num1);
printf ("Input value for num2: ");
scanf ("%d", &num2);
int prod =0, i;
for(i = 1; i <= num1; i++){
prod += num2;
}
int quo = 0 , rem = 0;
for(rem = num1 - num2; rem >= 0; rem = rem-num2) {
if(rem < 0)
break;
else
quo++;
}
//The last part is that i need to find the remainder without using multiplication, division and the modulo itself.
printf ("The product of %d and %d is: %d\n", num1, num2, prod);
printf ("The integer quotient of %d and %d is: %d\n", num1, num2, quo);
return 0;
}
If you want a slow calculation of num1 % num2
(ie without multiplication/division) you can do:如果您想要缓慢计算num1 % num2
(即没有乘法/除法),您可以执行以下操作:
// Calculate num1 % num2
unsigned rem(unsigned num1, unsigned num2)
{
if (num2 == 0) {.... error handling ....}
while (num1 >= num2) num1 -= num2;
return num1;
}
int main(void)
{
unsigned num1 = 42;
unsigned num1 = 3;
unsigned rem = rem(num1, num2);
printf("%u", rem);
return 0;
}
The simplest solution for calculating a mod b
for positive integers a
and b
with only subtraction and addition is to subtract b
from a
until the result is smaller than a
.仅通过减法和加法计算正整数a
和b
a mod b
的最简单解决方案是从a
中减去b
直到结果小于a
。 However, this takes many iterations if b
is much smaller than a
.但是,如果b
远小于a
,则需要多次迭代。
A method with better worst-case performance is the following:具有更好的最坏情况性能的方法如下:
#include <stdio.h>
unsigned rem(unsigned a, unsigned b)
{
if(b == 0) return 0; // Error
while(a >= b)
{
unsigned s = b;
do
{
a = a - s;
s = s + s;
} while(a >= s);
}
return a;
}
int main(void)
{
unsigned example = rem(32453, 3);
printf("%u\n", example);
}
This method is based on the fact that to get closer to the result, we can subtract any multiple of b
as long as it is smaller than a
, so in each inner iteration we try to subtract twice the multiples of the last iteration until the subtractor becomes too large and we start over again with a single multiple of b
.该方法基于这样一个事实,即为了更接近结果,我们可以减去b
的任意倍数,只要它小于a
,因此在每次内部迭代中,我们尝试减去上一次迭代的倍数的两倍,直到减法器变得太大,我们从b
的单个倍数重新开始。
Be aware that this will give wrong results if s = s + s;
请注意,如果s = s + s;
overflows the unsigned
range.溢出unsigned
范围。 Hence, a
should not be larger than half the upper limit of unsigned
.因此, a
不应大于unsigned
上限的一半。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.