Nil*_*nck 5 language-agnostic embedded math
我正在进行一个嵌入式项目,我必须将超时值写入某个微芯片的两个字节寄存器.
超时定义为:
timeout = REG_a * (REG_b +1)
Run Code Online (Sandbox Code Playgroud)
我想使用256的范围内的整数来编程这些寄存器,比方说60000.我正在寻找一种算法,给定超时值,计算REG_a和REG_b.
如果不可能得到确切的解决方案,我希望得到下一个可能更大的超时值.
到目前为止我做了什么:
我目前的解决方案是:
temp = integer_square_root (timeout) +1;
REG_a = temp;
REG_b = temp-1;
Run Code Online (Sandbox Code Playgroud)
这导致在实践中有效的值.但是,我想看看你们是否可以提出更优化的解决方案.
哦,我受内存限制,所以大表是不可能的.运行时间也很重要,所以我不能简单地强制解决问题.
小智 3
您可以使用该答案算法中使用的代码来查找给定数字的因子..最短方法?找到超时因素。
n = timeout
initial_n = n
num_factors = 1;
for (i = 2; i * i <= initial_n; ++i) // for each number i up until the square root of the given number
{
power = 0; // suppose the power i appears at is 0
while (n % i == 0) // while we can divide n by i
{
n = n / i // divide it, thus ensuring we'll only check prime factors
++power // increase the power i appears at
}
num_factors = num_factors * (power + 1) // apply the formula
}
if (n > 1) // will happen for example for 14 = 2 * 7
{
num_factors = num_factors * 2 // n is prime, and its power can only be 1, so multiply the number of factors by 2
}
REG_A = num_factor
Run Code Online (Sandbox Code Playgroud)
第一个因素是您的 REG_A,因此您需要找到另一个乘以等于超时的值。
for (i=2; i*num_factors != timeout;i++);
REG_B = i-1
Run Code Online (Sandbox Code Playgroud)