用 C++ 统计将一个数表示为连续数之和的方法数


给定一个整数 n 作为输入。目标是找到将 'num' 表示为两个或多个连续自然数之和的方法数。例如,如果 n 为 3,它可以表示为和 (1+2),所以共有 1 种方法。

例如

输入

num=6

输出

Count of ways to express a number as sum of consecutive numbers are: 1

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

解释

The ways in which we can express ‘num’ as sum of consecutive natural
numbers: 1+2+3

输入

num=19

输出

Count of ways to express a number as sum of consecutive numbers are: 1

解释

The ways in which we can express ‘num’ as sum of consecutive natural
numbers: 9+10

以下程序中使用的思路如下

在这种方法中,我们将数字表示为 (a + a+1 + a+2…..+ a+i) 的和。

它变成 (a)(L+1) 次 + 1+2+3+4…+i = a*(i+1) + i*(i+1)/2。(i 个自然数的和)num=a*(i+1) + i*(i+1)/2。a= [ num − (i)*(i+1)/2 ] / (i+1)

我们将从 i=1 到 i*(i+1)/2 小于 num 执行此操作。

  • 将一个整数 num 作为输入。

  • 函数 sum_consecutive(int num) 获取一个 num 并返回将 'num' 表示为连续自然数之和的方法数。

  • 将初始计数设置为 0。

  • 将临时变量 res 作为浮点数。

  • 使用 for 循环从 i=1 遍历到 i*(i+1)/2 < num。

  • 计算 [ num − (i)*(i+1)/2 ] / (i+1) 的值并将其存储在 res 中。

  • 如果 res 是整数(res − (int)res 为 0),则递增计数。

  • 最后,我们将计数作为将 num 表示为连续自然数之和的方法数。

  • 返回计数作为结果。

示例

 实时演示

#include <bits/stdc++.h>
using namespace std;
int sum_consecutive(int num){
   int count = 0;
   int temp = num * 2;
   float res;
   for (int i = 1; i * (i + 1) < temp; i++){
      int store = i + 1;
      res = (1.0 * num−(i * (i + 1)) / 2) / store;
      float check = res  (int)res;
      if(check == 0.0){
         count++;
      }
   }
   return count;
}
int main(){
   int num = 20;
   cout<<"Count of ways to express a number as sum of consecutive numbers are: "<<sum_consecutive(num) << endl;
   return 0;
}

输出

如果我们运行上述代码,它将生成以下输出:

Count of ways to express a number as sum of consecutive numbers are: 1

更新于:2021-01-05

738 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告