首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >算法 – 求和为n的连续正整数序列(C++)

算法 – 求和为n的连续正整数序列(C++)

作者头像
全栈程序员站长
发布2022-07-10 13:08:38
发布2022-07-10 13:08:38
8090
举报

大家好,又见面了,我是全栈君。

代码语言:javascript
复制
//****************************************************************************************************
//
//  求和为n的连续正整数序列 - C++ - by Chimomo
//
//  题目: 输入一个正整数n,输出全部和为n的连续正整数序列。比如:输入15,因为1+2+3+4+5=4+5+6=7+8=15,所以输出3个连续序列1-5、4-6和7-8。////  Answer: Suppose n = i+(i+1)+...+(j-1)+j, then n = (i+j)(j-i+1)/2 = (j*j-i*i+i+j)/2 => j^2+j+(i-i^2-2n) = 0 => j = (sqrt(1-4(i-i^2-2n))-1)/2 => j = (sqrt(4i^2+8n-4i+1)-1)/2.//          We know 1 <= i < j <= n/2+1, so for each i in [1,n/2], do this arithmetic to check if there is a integer answer.////  Note: 二次函数 ax^2+bx+c=0 的求根公式为: x = (-b±sqrt(b^2-4ac)) / 2a。////****************************************************************************************************#include <iostream>#include <cassert>#include <stack>#include <math.h>using namespace std ;int FindConsecutiveSequence(int n){	int count = 0;	for (int i = 1; i <= n/2; i++)	{		double sqroot = sqrt(4*i*i + 8*n - 4*i + 1);		int floor = sqroot;		if(sqroot == floor)		{			cout << i << "-" << (sqroot - 1) / 2 << endl;			count++;		}	}	return count;}int main(){	int count = FindConsecutiveSequence(15);	cout << "Totally " << count << " sequences found." << endl;	return 0;}// Output:/*1-54-67-8Totally 3 sequences found.*/

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/115523.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年2月3,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档