-2

I just want to add the sqrt of n to the divisors vector if its integer but everytime I try the code It goes Haywire. My vector.push_back(sqrt(n)) Function is giving the problem I sense.

Runtime error occurs . But when I remove those 3 Lines it works Fine.

Been trying for a long time!

INPUT - 1 100 8 23 11

I NEED HELP!

#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;
}

Thanks A Lot!

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Akhil Vaid
  • 11
  • 1
  • 10

1 Answers1

2
ll endd=diviors.size();
// ...
for (ll j = 0; j <= endd; j++) 
// ...            ^
    divisors[j]

When j = ennd you access out of the vector

François Andrieux
  • 28,148
  • 6
  • 56
  • 87
  • Wouldn't this imply an `IndexOutOfRange` exception instead of a timeout? – Rafalon Feb 21 '18 at 15:15
  • 1
    @Rafalon That's undefined behavior and the result could be anything. `IndexOutOfRange` is something a platform might do if it's able to detect the error, but it's not something you should expect or rely on. Perhaps you are thinking of [`std::out_of_range`](http://en.cppreference.com/w/cpp/error/out_of_range) that can be thrown by the `at` functions. – François Andrieux Feb 21 '18 at 15:17
  • @FrançoisAndrieux well I've done too much C# and got used to well defined and explicit exceptions. Still I don't understand why the OP mentioned a **timeout**. – Rafalon Feb 22 '18 at 07:53