算法 求和为n的连续正整数序列 C

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               
//****************************************************************************************************////  求和为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 = 0for (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." << endlreturn 0;}// Output:/*1-54-67-8Totally 3 sequences found.*/
           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow

这里写图片描述

猜你喜欢

转载自blog.csdn.net/yffhhffv/article/details/83820458