整數分解成多個連續的整數序列

來源:互聯網
上載者:User

題目描述:將一個正整數表示為n(n>=2)個連續正整數之和,如:
15=1+2+3+4+5
15=4+5+6
15=7+8
輸入任何一個正整數,找出符合這種要求的所有連續正整數序列。

如果沒有找到,剛輸出NULL 

分析:利用差數列公式求解,假設輸入整數n,n=(a1+a2)*(a2-a1+1)/2,0<a1<a2<n。

基於這個方法,不難寫出如下代碼:

void separateIntoItems(long n) {if (n <= 2) {System.out.println("NULL");return;}double max = Math.pow(2, 64);if ((double) n > max) {System.out.println("NULL");return;}boolean isExist = false;// a1 is the first numberfor (int a1 = 1; a1 <= n / 2; a1++) {// a2 is the last numberfor (int a2 = a1 + 1; a2 < n; a2++) {// if exist output the resultif ((a1 + a2) * (a2 - a1 + 1) == n * 2) {isExist = true;System.out.print(a1);for (int t = a1 + 1; t <= a2; t++) {System.out.print(" " + t);}System.out.println();}}}if (!isExist) {System.out.println("NULL");}}

轉載請註明本文出處:http://blog.csdn.net/love254443233

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.