【问题标题】:Simplify square roots algebraically以代数方式简化平方根
【发布时间】:2012-05-08 05:08:16
【问题描述】:

我想用代数简化整数的平方根,而不是用数值计算,即 √800 应该是 20√2 ,而不是 28.2842712474619。

我找不到任何通过编程解决这个问题的方法:(

【问题讨论】:

  • 你能写下人类采取的步骤吗?这是第一个任务。
  • 你的意思是一些符号系统(模块)吗?请看code.google.com/p/sympy

标签: c++ c algorithm square-root


【解决方案1】:

因式分解根下的数,选出成对出现的因式,其余的留在根下。

√800 = √(2 x 2 x 2 x 2 x 5 x 2 x 5) = √(22 x 22 x 52 x 2) = (2 x 2 x 5)√2 = 20√2。

为了完整起见,这里有一些简单的代码:

outside_root = 1
inside_root = 800
d = 2
while (d * d <= inside_root):
  if (inside_root % (d * d) == 0): # inside_root evenly divisible by d * d
    inside_root = inside_root / (d * d)
    outside_root = outside_root * d
  else:
    d = d + 1

当算法终止时,outside_root 和 inside_root 包含答案。

这里用 800 运行:

 inside   outside   d
    800         1   2 # values at beginning of 'while (...)'
    200         2   2
     50         4   2
     50         4   3
     50         4   4
     50         4   5
      2        20   5 # d*d > 2 so algorithm terminates
     ==        ==

答案 20√2 在最后一行。

【讨论】:

  • @Johnsyweb 我想如果我选择这个作为答案,没有人会表现出用其他方式解决这个问题的兴趣,所以只是等待:)
  • @antti.huima 你能检查一下我的代码吗,不知道有没有bug :|
  • @Sourav 是否有输入返回错误的代码答案?
  • @Sourav 如果您不知道它是否正常工作,请对其进行大量测试。如果这是家庭作业,我不想复习它。
【解决方案2】:
#include<stdio.h>
#include<conio.h>
int main() {
    int i, n, n2, last, final;
    last = 0, final = 1;
    printf("Enter number to calculate root: ");
    scanf("%d", & n);
    n2 = n;
    for (i = 2; i <= n; ++i) {
        if (n % i == 0) {
            if (i == last) {
                final = final * last;
                last = 0;
            } else {
                last = i;
            }
            n /= i;
            i--;
        }
    }
    n = n2 / (final * final);
    printf("\nRoot: (%d)^2 * %d", final, n);
    getch();
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多