Manas Bhardwaj
Manas Bhardwaj

Reputation: 1

Why does loop runs 1 or 2 times only when I use rand() function in c++

I want to generate random test cases for my program, but it crashes after running 1 or 2 times. I have used rand() function to generate random numbers for random test cases but it is not running after one or sometimes two times.. and does not generate any random number. The program simply exits.

#include<bits/stdc++.h>
#include<ctime>
#include <time.h>
using namespace std;

long long int naive(long long int arr[],long long int n){
    long long int max=-1;
    for(long long int i=0;i<n;i++)
    {
        for(long long int j=0;j<n;j++){
            if(arr[i]%arr[j] > max){
                max = arr[i]%arr[j];
            }
        }
    }
    return max;
}

long long int efficent(long long int arr[],long long int n){
    long long int max1=0,max2=0;
    for(long long int i=0;i<n;i++){
         if (arr[i] > max1) 
        { 
            max2 = max1; 
            max1 = arr[i]; 
        } 
        else if (arr[i] > max2 && arr[i] != max1) 
            max2 = arr[i]; 
    }
    return max2%max1;
}

int main(){
    srand(time(0));
    long long int count=0;
    int t=10;
    while(t--){
      long long int n;
      n = rand()%10;
      long long int arr[n];
      for(long long int i=0;i<n;i++){
        arr[i] = rand()%10;
      }
      long long int a,b;
      a = naive(arr,n);
      b = efficent(arr,n);
      if(a == b)
        cout<<"Naive : "<<a<<"\tEfficent : "<<b<<"\n";
      else{
        cout<<"\nNot Equal."<<"\nCount : "<<++count<<endl;
        cout<<"Naive : "<<a<<"\tEfficent : "<<b<<"\n";
      }
    }
    return 0;
}

Upvotes: 0

Views: 76

Answers (2)

Tyler Marshall
Tyler Marshall

Reputation: 488

In addition to the memory leaks and not declaring a variable sized array correctly mentioned in the other answer, the issue is that you are performing the mod operation on values that could be 0. This will force your program to exit. To fix this, change

arr[i] = rand()%10;

to something like

arr[i] = rand()%10+1;

to prevent division by 0.

EDIT: as mentioned by @Michael Dorgan, you should probably do the same for n. Change

n = rand()%10;

to

n = rand()%10+1;

to prevent 0 length arrays from being allocated.

Upvotes: 2

xryl669
xryl669

Reputation: 3584

This code is problematic:

while(t--){
    long long int n;
    n = rand()%10;
    long long int arr[n];
    for(long long int i=0;i<n;i++){
    arr[i] = rand()%10;
    }

If you need a variable size array, you should use long long int * arr = new long long int[n]; and delete[] arr; before the last closing brace of the while block.

Upvotes: 0

Related Questions