计算一个数字的表示数,该数字是3个方格的总和

时间:2013-08-06 17:57:14

标签: c++ algorithm

我需要编写一个函数头,它返回一个数字的表示数,作为3个正方形的总和。

例如,3作为3个方格之和的唯一表示是3 = 1 + 1 + 1,因此如果number = 3,则函数应返回1.如果n为27,则函数应返回2,因为27具有两个表示27 = 25 + 1 + 1或9 + 9 + 9.

这就是我的尝试:

#include <iostream>
#include <cmath>
using namespace std;

int  numRep(int num);

int main()
{
   int count = numRep(27);
   cout << count;
   return 0;
}

int numRep(int num)
{
   int count = 0, sum = 0;
   int a =1, b=1, c=1;
   while(a*a <= num -2)
   {
     b = 1; 
     while(b*b <= num -2)
     {
       c =1;
       while(c*c <= num -2)
       {
         sum = a*a + b*b + c*c;
         if (sum == num) count++;
         c++;
       }
       b++;
     }
     a++;
   }
   return count/3;
}

但我没有得到正确的输出。需要一些指导...如果有更好的方法,请建议..

5 个答案:

答案 0 :(得分:7)

这是一个很好的起点:

#include <cmath>
#include <iostream>

int count_sum_of_squares(int n)
{
  int count=0;

  // We only need to test numbers up to and including the square root of n.
  // Also, we want to impose an ordering on [a, b, c] to consider 
  // combinations and NOT permutations.
  for (int a=1; a<=int(sqrt(n)); ++a)
    for (int b=1; b<=a; ++b)
      for (int c=1; c<=b; ++c)
        if (a*a+b*b+c*c==n) // If the squares of {a, b, c} add up to n
          ++count;          // then this is a case that should be counted

  return count;
}

int main()
{
  std::cout << 3 << ': ' << count_sum_of_squares(3) << '\n';
  std::cout << 14 << ': ' << count_sum_of_squares(14) << '\n';
  std::cout << 27 << ': ' << count_sum_of_squares(27) << '\n';
  std::cout << 866 << ': ' << count_sum_of_squares(866) << '\n';
}

答案 1 :(得分:2)

您应该只搜索上面的当前索引循环,而不是从1到num - 2进行搜索。这样,您就不会重复任何条款。

#include <iostream>
#include <cmath>
using namespace std;

int  numRep(int num);

int main()
{
   int count = numRep(27);
   cout << count << endl;
   return 0;
}

int numRep(int num)
{
   int count = 0, sum = 0;
   int a =1, b=1, c=1;
   while(a*a <= num -2)
   {
     b = a; 
     while(b*b <= num -2)
     {
       c =b;
       while(c*c <= num -2)
       {
         sum = a*a + b*b + c*c;
         if (sum == num) {
            count++;
         }
         c++;
       }
       b++;
     }
     a++;
   }
   return count;
}

答案 2 :(得分:1)

你得到了所有的排列,你想要所有的组合。

示例:当我认为你想让它只有1时,numRep(14)会给你6个。

a = 1, b = 2, c = 3
a = 1, b = 3, c = 2
a = 2, b = 1, c = 3
a = 2, b = 3, c = 1
a = 3, b = 1, c = 2
a = 3, b = 2, c = 1

你需要跟踪你的答案,最好用a-c从最低到最高排序,如果已经存在,不要增加你的计数。

答案 3 :(得分:1)

这对我有用:

 int numRep(int num){

   int count = 0;

   for(int a = 1; a * a <= num ; ++a)
        for(int b = a; b * b <= num ; ++b)
            for(int c = b; c * c <= num ; ++c)
                if (a*a + b*b + c*c == num) 
                    count++;

   return count;
}

仅从b的{​​{1}}和a的{​​{1}}开始,因此您不会计算两次相同的解决方案。

我认为这是c的复杂性。

答案 4 :(得分:0)

a开始第二次循环。而且你根本不需要第三个循环。 c = sqrt(num - a*a - b*b)。如果计算出的c是一个整数,则它会计算。