查找数组表示中的数字模数和除数

时间:2018-04-27 12:17:05

标签: c math

我有一个无符号整数数组,如下所示

unsigned modulo(unsigned coeffs*, unsigned degree, unsigned divisor)
{
    int r = 0;
    for(int i = 0; i < degree; ++i)
        r = (r * 10 + coeffs[i]) % divisor;
    return r;
}

表示数字&lt; x_(n-1)... x_1 x_0&gt;以基地10。

现在我想在给定除数(无符号整数)的情况下找出这个数的模数,并想出了使用Horner规则用C编写的以下函数。

driver.findElement(By.xpath("unique_xpath_of_webelement"));

这是正确的还是我在这里做错了什么? x)的

1 个答案:

答案 0 :(得分:1)

  

查找数组表示中的数字模数和除数
  这是正确的还是我在这里做错了什么?

divisor,没问题。

当大divisor代码失败时,

@Klas Lindbäck被识别出来。 (假设使用了unsigned r而不是int r)。我得出了一个略有不同的限制

divisor <= (UINT_MAX - 9)/10 + 1

如果代码需要处理大divisor,那么有两种方法:

1)使用更广泛的类型:

// Consider some wider type like unsigned long long or uintmax_t
_Static_assert(ULLONG_MAX > UINT_MAX, "Oops");
typedef unsigned long long unsigned2x;

// Might as well make `unsigned coeffs*` `const`  and `size_t` for indexing.
unsigned modulo(const unsigned coeffs*, size_t degree, unsigned divisor) {
  unsigned2x r = 0;
  for(size_t i = 0; i < degree; ++i) {
    r = ((r * 10) + coeffs[i]) % divisor;
  }
  return (unsigned) r;
}

2)在部分中执行 mod

r * 10溢出时,@Micrified提供的方法失败。

为了应对没有更宽的无符号整数并且代码必须处理大divisor的情况,请使用下面的代码来使用Modular exponentiation without range restriction中的代码

// when `unsigned` potentially as wide as `uintmax_t`
unsigned modulo(const unsigned coeffs*, size_t degree, unsigned divisor) {
  unsigned r = 0;
  for(size_t i = 0; i < degree; ++i) {
    r = mulmodmax(r, 10, divisor);
    r = addmodmax(r, coeffs[i], divisor);
  }
  return r;
}