Algorithm basics: Integer split problem (Golang implementation)

Source: Internet
Author: User

An integer can always be split into the sum of 2 powers, for example:

7=1+2+4
7=1+2+2+2
7=1+1+1+4
7=1+1+1+2+2
7=1+1+1+1+1+2
7=1+1+1+1+1+1+1

There are 6 different ways to split.
Another example: 4 can be split into: 4 = + = 1 + 1 + 1 + 1,4 = 2 + 2,4=1+1+2.
Use f (n) to denote the number of different splits of N, such as F (7) =6.
Requires programming, read N (not more than 1000000), output f (n)

Input: An integer N (1<=n<=1000000).
Output: F (n)
Input data if out of range, output-1.

Sample input:
7

Sample output:
6
Code implementation:

 PackageHuaweiImport("FMT")funcTest08base () {Input: =1000000Output: = Numbersplit (input) fmt. PRINTLN (Output)}funcNumbersplit (nint)int{ifN <1|| n >1000000{return-1}//1=1,1 method of splitting    ifn = =1{return1}//2=2,2=1+1,2 method of splitting    ifn = =2{return2}//n>=3    //Save the calculated valuesData: = Make([]intN+1) data[0] =0 //This value has no meaning for pure placeholder actionData[1] =1Data[2] =2     forI: =3; I <= N; i++ {ifI%2==0{//EvenData[i] = Data[i-2] + data[i/2]        }Else{//OddData[i] = Data[i-1]        }    }returnData[n]}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Algorithm basics: Integer split problem (Golang implementation)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.