求出和为固定值的所有连续整数

本文介绍了一种通过双指针方法寻找所有连续整数序列,这些序列的和等于给定数值的算法实现。该算法使用C语言编写,通过逐步调整左右指针的位置来找出所有可能的整数序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定和为n,两个指针 l、r从0到n扫描, 记录sum=a[l]+……+a[r]。if sum<n r++; if sum>n l++; if(sum==n) output,  r++,l++;


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

void main(void)
{
     long  left, right;       /* left and right bound     */
     long  sum;               /* computed sum             */
     long  GIVEN;             /* the given number         */
     int   count = 0;         /* solution counter         */
     char  line[100];         /* input buffer             */

     printf("\nConsecutive sum to a fixed given number");
     printf("\n=======================================\n");
     printf("\nYour number (> 0) please ---> ");
     gets(line);
     GIVEN = atol(line);

     for (sum = 0, right = 1; sum < GIVEN; sum += right, right++)
          ;

     for (left = 1, right--; left <= GIVEN/2; )
          if (sum > GIVEN)         /* if sum too large    */
               sum -= (left++);    /* reduce from left    */
          else {
               if (sum == GIVEN) { /* if equal, print it  */
                    printf("\n%ld = sum from %ld to %ld",
                           GIVEN, left, right);
                    count++;       /* and increase count  */
               }                   /* if sum too small    */
               sum += (++right);   /* increase from right */
          }

     if (count > 0)
          printf("\n\nThere are %d solutions in total.", count);
     else
          printf("\n\nSorry, there is NO solution at all.");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值