-2

I have searched google but I was unable to find the solution to my problem. Here is my code-

#include <bits/stdc++.h>
#include<algorithm>
#include<cstdlib>
#include<cstdio>

using namespace std;

long long buyMaximumProducts(int n, long k, vector <int> a) {
    // Complete this function
    vector<pair<int, int>> p;
    long i;
    for(i=0; i<n; i++) {
        p.push_back(make_pair(a[i], i+1));
    }

    sort(p.begin(), p.end());

    if(k < p[0].first)
        return 0;

    long long sum=0,stocks=0;

    for(i=0;i<n;i++)
    {
        if((sum+p[i].first*p[i].second) <= k)
        {
            sum+=p[i].first*p[i].second;
            stocks+=p[i].second;
        } 
        else 
            break; 
    }

    long long amtleft=k-sum;
    **stocks+=(long long)(amtleft/p[i].first);**
    return stocks;

}

int main() {
    int n;
    cin >> n;
    vector<int> arr(n);
    for(int arr_i = 0; arr_i < n; arr_i++){
       cin >> arr[arr_i];
    }
    long long k;
    cin >> k;
    long long result = buyMaximumProducts(n, k, arr);
    cout << result << endl;
    return 0;
}

I'm getting floating point exception. I think the error is coming because of the star statement. Can anyone please tell me what could be the plausible reason and how to remove it?

1 Answers1

0

The program contains at least 3 fault.

long long k;
cin >> k;
long long result = buyMaximumProducts(n, k, arr);

long long buyMaximumProducts(int n, long k, vector <int> a) {

k is 'long long' but parameter k is only 'long'.

for(i=0;i<n;i++) {
    if((sum+p[i].first*p[i].second) <= k) {
        sum+=p[i].first*p[i].second;
        stocks+=p[i].second;
    } else 
        break; 
}

if we never get to the 'break' then 'i' is not valid for

stocks+=(long long)(amtleft/p[i].first);

causing an exception.

and if

p[i].first

is zero you get an divide by zero exception.

Surt
  • 15,501
  • 3
  • 23
  • 39
  • 1
    How can they get a floating point exception if none the involved variables is of a floating point type? – Bob__ Aug 20 '17 at 09:44
  • 1
    That is a very good question, it should have been a divide by zero exception. – Surt Aug 20 '17 at 09:46