51Nod 2141 第N个智慧数 c/c++题解

题目描述

一个正整数如果能表示成两个正整数的平方差,则称这个数为一个“智慧数”,比如 16 就等于 5的平方减去 3 的平方,所以 16 就是一个智慧数,从 1 开始的自然数列中,将“智慧数”从小到大编号为 1,2,3,…,n。现输入一个正整数 n,输出第 n 个“智慧数”。
输入
输入仅包含一个正整数 n(1≤n≤100)。
输出
输出仅包含一个正整数,表示编号为 n 的“智慧数”。
输入样例
3
输出样例
7

题解:

本身不是一道难题,但是需要注意细节我的思路:就是求出100个自然数,然后直接输出即可,但是求的话范围的确定要注意,我的范围就是没有范围,直接求出100个然后才退出,再就是在枚举的过程中会出现很多重复的数而且是无序的,这里最好使用STL的set容器,保证了没有重复也直接排了序。
注意:这道题出的本身就有问题,给出的n的范围是1<=n<=100,但是只求100个智慧数根本过不了,求1000还是有两个点过不了,所以我直接求10000个,反正这里对时间也没什么要求。

代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <deque>
#include <list>
#include <utility>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <iterator>
using namespace std;

typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll  INF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double E = exp(1.0);
const int MOD = 1e9+7;
const int MAX = 1e2+5;
int n;

// 求出所有的智慧数
set <int> s;
void getAllNum()
{
    int cnt = 0;
    for(int i = 1; ; i++)
    {
        for(int j = 1; j < i; j++)
        {
            s.insert(i*i-j*j);
            if(s.size() == 10000)
                return;
        }
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    getAllNum();

    while(cin >> n)
    {
        int cnt = 0;
        for(auto it = s.begin(); it != s.end(); it++)
        {
            cnt++;
            if(cnt == n)
                cout << *it << endl;
        }
    }

    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值