math - 将整数分解为两个字节

标签 math language-agnostic embedded

我正在做一个嵌入式项目,我必须将超时值写入一些微芯片的两个字节寄存器中。

超时定义为:

   timeout = REG_a * (REG_b +1)

我想使用 256 范围内的整数对这些寄存器进行编程,比如 60000。我正在寻找一种算法,该算法在给定超时值的情况下计算 REG_a 和 REG_b。

如果不可能有确切的解决方案,我想获得下一个可能的更大超时值。

到目前为止我做了什么:

我目前的解决方案计算:
   temp = integer_square_root (timeout) +1;
   REG_a = temp;
   REG_b = temp-1;

这导致在实践中运行良好的值。但是,我想看看你们是否可以提出更优化的解决方案。

哦,我的内存有限,所以大表是不可能的。运行时间也很重要,所以我不能简单地强制解决方案。

最佳答案

您可以使用该答案中使用的代码 Algorithm to find the factors of a given Number.. Shortest Method?找到超时因素。

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

第一个因素将是您的 REG_A,因此您需要找到另一个乘以等于超时的值。
for (i=2; i*num_factors != timeout;i++);
REG_B = i-1

关于math - 将整数分解为两个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15851834/

相关文章:

algorithm - 算法中的不熟悉的符号 : what does ∀ mean?

c - 通过单个 GPIO 引脚转储闪存

c - 如何用 C 实现分层并发有限状态机 (HCFSM)?

c - 如何改进 Nios 2 的临时巡航控制系统?

java - 两个整数乘积的模数

algorithm - 对给定的成对排序进行排序

math - 是否有任何 x 的 SHA1(x) 等于 x?

algorithm - 空间(槽)优化算法

windows - 为所有用户存储具有读\写权限的应用程序数据的最佳目录?

regex - 用于在条件语句中查找意外赋值的正则表达式