2015 Huawei Machine Test--integer segmentation

Source: Internet
Author: User

Title Description:

An integer can 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 six different ways to split
Another example: 4 can be split into: 4 = 4, 4 = 1+1+1+1, 4 =, 4 = 1+1+2.
use f (n) to denote the number of different splits of N, such as f (7) = 6.
required to read n (not more than 1000000), output f (n)% 1000000000.


Problem Solving Ideas:

For odd n = 2k+1, the first item of its split must be 1, consider removing this 1, in fact one by one corresponds to the split of 2k, so f (2k+1) = f (2k).
For even n = 2k: Consider a split of 1 and No 1. There is a 1 split, corresponding to the (2k-1) split one by one, the same as the above odd case: There is no 1 split, dividing each item by 2, exactly one by one corresponds to all splits of K, so f (2k) = f (2k-1) + f (k).
The end result is only required to divide the remainder by 1 billion, in the representation range of int, and therefore does not require a large number operation. Note the nature of the remainder: (a+b)%m = (a%m+b%m)%m, so as long as the remainder is taken for each intermediate result, there is no overflow problem and the final output is not changed.


The code is as follows:

public static void Main (string[] args) {Scanner sc=new Scanner (system.in), while (Sc.hasnext ()) {int input=sc.nextint (); Fenge (input);} Sc.close ();} public static void Fenge (int n) {list<integer> list=new arraylist<integer> (); list.add (0); if ((N>=1) && (n<=1000000)) {for (int i = 1; I <= n; i++) {if (i%2==1) {if (i==1) {list.add (1);} Else{list.add (List.get (i-1));}} if (i%2==0) {List.add ((List.get (i-1) +list.get (I/2))%100000000);}} System.out.println (List.get (n));} Else{system.out.println (-1);}}

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

2015 Huawei Machine Test--integer segmentation

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.