【问题标题】:Why does my code give runtime error timeout?为什么我的代码会给出运行时错误超时?
【发布时间】:2018-02-21 15:00:57
【问题描述】:

我只想将 n 的 sqrt 添加到除数向量,如果它是整数,但每次我尝试代码时它都会乱码。 我的 vector.push_back(sqrt(n)) 函数给出了我感觉到的问题。

发生运行时错误。但是当我删除这 3 行时,它工作正常。

试了好久!

输入 - 1 100 8 23 11

我需要帮助!

#include <bits/stdc++.h>
#include <stdio.h>
#include <iostream>

#define ll long long int
#define li long int

using namespace std;

bool isPerfectSquare(long long n) {
  long long squareRootN = (long long)round((sqrt(n)));

  if (squareRootN * squareRootN == n) {
    return true;
  } else {
    return false;
  }
}
int main() {
  ios::sync_with_stdio(0);
  ll t;
  cin >> t;
  while (t--) {
    ll n, a, b, c;
    cin >> n;
    cin >> a >> b >> c;

    vector<ll> divisors;
    for (ll i = 1; i < sqrt(n); i++) {
      if (n % i == 0) {
        divisors.push_back(i);
        if ((n / i) != i)
          divisors.push_back(n / i);
      }
    }
    // HEREEEEEEE ISS THE PROBLEMMMM
    ll y = sqrt(n);
    if (isPerfectSquare(n))
      divisors.push_back(y);

    ll z = divisors.size();
    for (ll i = 0; i < z; i++)
      cout << divisors[i] << ' ';

    sort(divisors.begin(), divisors.end());
    cout << '\n';

    ll x = divisors.size();
    for (ll i = 0; i < x; i++)
      cout << divisors[i] << ' ';

    ll endd = divisors.size();

    ll counter = 0;
    for (ll i = 0; i < endd; i++) {
      for (ll j = 0; j <= endd; j++) {
        if (n % (divisors[i] * divisors[j]) == 0 &&
            n / (divisors[i] * divisors[j]) <= c && divisors[i] <= a &&
            divisors[j] <= b) {
          cout << '\n'
               << divisors[i] << ' ' << divisors[j] << ' '
               << n / (divisors[i] * divisors[j]);
          counter++;
        }
      }
    }

    cout << '\n' << counter << '\n';
  }
  return 0;
}

非常感谢!

【问题讨论】:

  • 要求某人审查使用#define li long int 的代码并不好。你真的认为这会增加清晰度和可读性吗?
  • 你对tn有什么意见?
  • 我不知道任何可能导致超时错误的标准机制,并且提供的代码中没有任何内容表明它也可能。
  • 在线编码判断是调试程序的错误工具。我觉得这是常识,如果我想要一个 long long int 我写 long long int 而不是一个神秘的 2 字母名称

标签: c++ vector square-root


【解决方案1】:
ll endd=diviors.size();
// ...
for (ll j = 0; j <= endd; j++) 
// ...            ^
    divisors[j]

当 j = ennd 你访问出向量

【讨论】:

  • 这不是意味着IndexOutOfRange 异常而不是超时吗?
  • @Rafalon 这是未定义的行为,结果可能是任何东西。 IndexOutOfRange 是平台如果能够检测到错误可能会做的事情,但这不是您应该期望或依赖的事情。也许您正在考虑可以由at 函数抛出的std::out_of_range
  • @FrançoisAndrieux 好吧,我已经做了太多 C# 并且习惯了明确定义和明确的异常。我仍然不明白为什么 OP 提到了 超时
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-13
  • 2020-11-11
  • 1970-01-01
  • 2021-12-31
  • 2021-06-25
  • 2020-12-15
相关资源
最近更新 更多