华为机试题——HJ76 尼科彻斯定理

描述

验证尼科彻斯定理,即:任何一个整数m的立方都可以写成m个连续奇数之和。

例如:

1^3=1

2^3=3+5

3^3=7+9+11

4^3=13+15+17+19

输入一个正整数m(m≤100),将m的立方写成m个连续奇数之和的形式输出。

数据范围:1\le m\le 100\1≤m≤100 

进阶:时间复杂度:O(m)\O(m) ,空间复杂度:O(1)\O(1) 

输入描述:

输入一个int整数

输出描述:

输出分解后的string

示例1

输入:

6

复制输出:

31+33+35+37+39+41
#include <iostream>
#include <vector>
#include <sstream>
std::string itoa(int num)
{
    std::stringstream oss;
    oss <<  num;
    return oss.str();
}

void nikochus(int n)
{
    int coub = n * n * n;
    int tempi = n * n - n + 1;          //记录每次开始累加的坐标
    if(tempi % 2 == 0)
    {
        tempi -= 1;
    }
    std::vector<std::string> rtnVect;
    while(1)
    {
        int sum = 0;
        int start = tempi;
        while(start < coub / 2)
        {
            sum += start;
            start += 2;
            int end = start;
            if(sum == coub)
            {
                for(int k = tempi; k < end; k += 2)
                {
                    rtnVect.push_back(itoa(k));
                    rtnVect.push_back("+");
                }
                
                std::vector<std::string>::iterator iter = rtnVect.begin();
                while(iter != rtnVect.end()-1)
                {
                    std::cout << *iter++;
                }
                std::cout << std::endl;
                return;
            }
            if(sum > coub)
            {
                break;
            }
        }
        tempi += 2;
        sum = 0;
    }

    // print(rtnVect);
}

//6         31+33+35+37+39+41
int main()
{
    int n;
    while(std::cin >> n)
    {
        nikochus(n);
    }

    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值