• 九度oj 题目1354:和为S的连续正数序列


    题目描述:

    小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!

    输入:

    输入有多组数据。

    每组数据仅包括1个整数S(S<=1,000,000)。如果S为负数时,则结束输入。

    输出:

    对应每组数据,若不存在和为S的连续正数序列,则输出“Pity!”;否则,按照开始数字从小到大的顺序,输出所有和为S的连续正数序列。每组数据末尾以“#”号结束。

    样例输入:
    4
    5
    100
    -1
    样例输出:
    Pity!
    #
    2 3
    #
    9 10 11 12 13 14 15 16
    18 19 20 21 22
    #

    如果用遍历的话肯定会超时,这个题应该用数学公式求解
    假设有m个连续的数,则
    求和(x ~ x +m -1) = n
    可得到x 和n , m的关系,枚举m,可得解
    因为 x > 0 , 可得m < (sqrt(1 + 8 * n) + 1)/2;
    代码如下
     1 #include <cstdio>
     2 #include <cstdlib>
     3 #include <cstring>
     4 #include <iostream>
     5 #include <algorithm>
     6 #include <cmath>
     7 
     8 using namespace std;
     9 typedef long long ll;
    10 
    11 int main(int argc, char const *argv[])
    12 {
    13     int n, k;
    14     while(scanf("%d",&n) != EOF && n >= 0) {
    15         bool isFind = false;
    16         int ta = 2 * n;
    17         int m = (sqrt(1 + 8 * n) + 1)/2;
    18         //int m = sqrt(2.*n)+1;
    19         for(int i = m; i >= 2; i--) {
    20             if(ta % i != 0) {
    21                 continue;
    22             }
    23             
    24             int tb = ta/i + 1 - i;
    25             if(tb <= 0) {
    26                 continue;
    27             }
    28             if(tb & 1) {
    29                 continue;
    30             }
    31             int x = tb/2;
    32 
    33             printf("%d",x);
    34             for(int p = 1; p < i; p++) {
    35                 printf(" %d",x+p);
    36             }
    37             puts("");
    38             isFind = true;
    39         }
    40         if(!isFind) {
    41             puts("Pity!");
    42         }
    43         
    44         puts("#");
    45     }
    46     return 0;
    47 }
  • 相关阅读:
    winform中利用正则表达式得到有效的电话/手机号
    winform运行时如何接受参数?(示例)
    [基础]Javascript中的继承示例代码
    [转]C#中"is" vs "as"
    Javascript数组常用方法[包含MS AJAX.NET的prototype扩展方法]示例
    linq学习笔记(一)
    用winform应用程序登录网站的解决方案
    [转贴]操纵自如--页面内的配合与通信
    .net3.0中的扩展方法(示例)
    window.location或window.open如何指定target?
  • 原文地址:https://www.cnblogs.com/jasonJie/p/5804307.html
Copyright © 2020-2023  润新知