《编程之美》读书笔记(十二):“只考加法的面试题”
[question]
我們知道:1+2=3;
??????????????4+5=9;
????????????? 2+3+4=9;
等式左邊都是兩個(gè)以上連續(xù)的自然數(shù)相加,那么是不是所有的整數(shù)都可以寫成這種形式呢?
寫一個(gè)程序,對于一個(gè)32位正整數(shù),輸出它所有的連續(xù)自然數(shù)之和的算式。
[analysis]
可以發(fā)現(xiàn)任意自然數(shù)序列其實(shí)是公差為1的等差數(shù)列,那么數(shù)列前N項(xiàng)和公式有a1*n +n*(n-1)/2 = sn,而這里sn = 輸入的正整數(shù)input。通過分析a1只需在集合[1,input/2)中,把上式等效變形為n2+(2a1-1)n-2input = 0,n的取值為中學(xué)學(xué)得2a分之負(fù)b加減根號下b方減4ac,哈,如果n為一個(gè)正整數(shù),那么符合條件輸出。如何判斷n為合法的正整數(shù)不是浮點(diǎn)數(shù)呢?看看我的solution吧。我算法的時(shí)間復(fù)雜度是O(N)線形級別的,不知哪位大蝦的solution可以再快些。
[answer-programme]
#include "stdafx.h"
#include <math.h>
#include <iostream.h>
bool isPositiveInt(float num)
{
return (num - (int)num)==0?true:false;
}
void outputResult(int a1,float n,int input)
{
? int loopCounter = 1;
? int a = a1;
? cout<<a1;
?
? while(loopCounter<(int)n)
? {
???? cout<<"+"<<a1+loopCounter++;
? }//while
?
? cout<<"="<<input<<endl;
}
int main(int argc, char* argv[])
{
unsigned int input,i;
//input any positive numbers you want to calculate with
cout<<"input any positive numbers you want to calculate with:"<<endl;
??????? cin>>input;
//O(n)
cout<<endl<<"the possible data groups are"<<endl;
float temp;
for(i=1;i<=input/2;i++)
{
??? temp = sqrt(8*input+(i+i-1)*(i+i-1));//b*b - 4ac
??? temp = (1 + temp - i - i)/2;
??? if(isPositiveInt(temp))
??? {
?????? outputResult(i,temp,input);
??? }
}
return 0;
}
轉(zhuǎn)載于:https://www.cnblogs.com/bvbook/archive/2008/11/18/1335742.html
總結(jié)
以上是生活随笔為你收集整理的《编程之美》读书笔记(十二):“只考加法的面试题”的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 环保招贴设计教案一等奖
- 下一篇: 对男朋友甜甜的情话217个