POJ 2140 Herd Sums

Herd Sumsjava

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 18461   Accepted: 10805

Descriptionthis

    The cows in farmer John's herd are numbered and branded with consecutive integers from 1 to N (1 <= N <= 10,000,000). When the cows come to the barn for milking, they always come in sequential order from 1 to N. 

    Farmer John, who majored in mathematics in college and loves numbers, often looks for patterns. He has noticed that when he has exactly 15 cows in his herd, there are precisely four ways that the numbers on any set of one or more consecutive cows can add up to 15 (the same as the total number of cows). They are: 15, 7+8, 4+5+6, and 1+2+3+4+5. 

    When the number of cows in the herd is 10, the number of ways he can sum consecutive cows and get 10 drops to 2: namely 1+2+3+4 and 10. 

Write a program that will compute the number of ways farmer John can sum the numbers on consecutive cows to equal N. Do not use precomputation to solve this problem. code

Inputip

* Line 1: A single integer: N ci

Outputget

* Line 1: A single integer that is the number of ways consecutive cow brands can sum to N. it

Sample Inputio

15

Sample Outputtable

4

Solution:class

    題目大意:給定一個正整數n,求連續正整數的和爲n的組數。好比對於15,有15,7+8, 4+5+6, 1+2+3+4+5, 共4種;對於10,有10, 1+2+3+4, 共2種。

    思路:按連續正整數的個數爲偶數和奇數進行分別考慮。若是爲奇數,那麼n必須可以整除這個奇數,好比15可以整除5(1,2,3,4,5,左右對稱),而且因爲都是正整數,爲了不出現0,1,2,3,4,5以及可能出現的帶負數的組合,須要另外補充一個條件 t - i / 2>0; 若是是偶數,那麼n/(i+0.0)獲得的數的小數位必定爲5,好比10/(4+0.0)=2.5, 而且因爲都是正整數,爲了不出現0,1,2,3,4以及可能出現的帶負數的組合,須要另外補充一個條件 t - i / 2>=0;

    最後的result+1是加上n本身這種狀況。

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        br.close();

        int result = 0;
        for (int i = 2; i <= n / 2; i++) {
            int t = n / i;
            if ((i & 01) == 1) { //奇數
                if (n % i == 0 && t - i / 2 > 0) {
                    result++;
                }
            } else { //偶數
                if (n % (2 * t + 1) == 0 && t - i / 2 >= 0) {
                    result++;
                }
            }
        }
        System.out.println(result + 1);
    }
}
相關文章
相關標籤/搜索