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);
    }
}
相关文章
相关标签/搜索