C - 找出数字的 a^2+b^2

标签 c numbers

我手头有一个问题,我无法弄清楚,因为我对 C 编程还很陌生。问题是找出100到999之间所有可以用(a^2 + b^2)形式表示的整数

这是我尝试过的:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
  int n,i,j,soln;

  for (n=100;n<1000;++n) {
    soln=0;

    for (i=0;i<100;++i) {
      for (j=i;j<100;++j) {
        if ((i^2 + j^2)==n) {
          soln=1;
        } else {
          soln=0;
        }
      }
    }

    if (soln==1) printf("%d is a solution.\n",n);
  }

  return EXIT_SUCCESS;
}

谢谢大家!

最佳答案

您的代码有两个问题:

<强>1。使用 * 对数字进行平方,而不是 ^

要在 C 中对数字求平方,请不要使用 ^ 运算符(这是按位异或运算符)。请改用 * 运算符:

if ((i*i + j*j)==n) {
   soln=1;
} else {
   soln=0;
}

<强>2。将 if 条件移到内部循环中

您的代码的另一个问题是您覆盖了 soln 值。您应该将条件移动到内部循环中:

for (n=100;n<1000;++n) {
  soln=0;

  for (i=0;i<100;++i) {
    for (j=i;j<100;++j) {
      if ((i*i + j*j)==n) {
        soln=1;
      } else {
        soln=0;
      }
      // Condition here. When it was in the outer loop level, 
      // the soln=1 would be overwritten to the 0 in the next iteration
      // and printf() wouldn't be called.
      if (soln==1) {
        printf("%d is a solution.\n",n);
        // To avoid printing multiple times for the same n,
        // break from the loop (loop for 'j').
        // If you would want to print for every i,j pair that meets
        // the criteria, remove this 'if' block, get rid of 'soln'
        // and print in the if above (where you square the numbers).
        break;
      }
    }
    // We need to break the two loops, for i and j. This one is for 
    // the outer loop ('i').
    if (soln == 1) break;
  }
}

如您所见,您可以通过两种略有不同的变体来实现:

  • 您只关心n - 如果您不需要知道解的数字的组成部分,您可以加快速度通过不打印所有可能的解决方案,只打印满足它的 n 来稍微改进算法。在那种情况下,一旦您找到一个 ij,当它们的平方为 n 时,只需打破这两个循环。你可以这样做,因为对于 n,我们知道存在满足条件的 i/j 对。

  • 您关心的是 n 和解方程的确切 i/j -在这种情况下,删除 soln 变量并只打印解决方案,而不是将 soln 设置为 1。

关于C - 找出数字的 a^2+b^2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25259762/

相关文章:

boost - 将 boost 随机数生成器与 OpenMP 结合使用

c - 'goto' 是否适合在 C(而非 C++)中正确使用堆栈变量

c++ - 在具有低级别访问权限的随身碟上写入

c - 我无法完美地完成这个循环

MySQL UPDATE 随机数在 1-3 之间

javascript - JavaScript 将长数字转换为缩写字符串,有特殊的短小要求

javascript - 在javascript中将数字数组转换为String()

java - java中的数字到字母(就像旧手机的键盘)

c++ - 为什么结构体的 sizeof 不等于每个成员的 sizeof 之和?

c - 为什么 & 在变量前使用?