Connecting Tech Pros Worldwide Forums | Help | Site Map

generating random numbers for 1,000,000 elements

Newbie
 
Join Date: Oct 2007
Location: Chicago
Posts: 9
#1: Oct 31 '07
In my code I want to be able to generate up to 1000000 numbers. Will my random number generator do this without crashing? If not, can someone assist me in what I need to do?

thank you

Expand|Select|Wrap|Line Numbers
  1. int main()
  2.     int num,i,elem, percent;
  3.     a[num];
  4.     cout<<"Please Enter THE NUMBER OF ELEMENTS you want to sort[THEN PRESS ENTER]:"<<endl;
  5.     cin>>num;
  6.     cout<<"Please Enter THE PERCENTAGE you want to sort[THEN PRESS ENTER]:"<<endl;
  7.     cin>>percent;
  8.     for (i=1; i<=num; i++)
  9.     {
  10.         elem =((rand()*9)+1);
  11.         cout<<endl<<"element "<<i<<"is "<<elem<<endl;
  12.         a[i]= elem;
  13.         cout<<"When i is "<<i<<" ai is "<<a[i];
  14.     }
  15.     merge_sort(1,num);
  16.     cout<<endl<<"So, the sorted list (using MERGE SORT) will be : "<<endl;
  17.     for(i=1;i<=num;i++)
  18.     {
  19.          cout<<a[i]<<" ";
  20.     }
  21.     cout<<endl<<"Time Elapsed is: "<<timeElapsed<<endl<<endl<<endl<<endl<<endl;
  22.     system("PAUSE");
  23. return 0;
  24. }

Ganon11's Avatar
Moderator
 
Join Date: Oct 2006
Location: New York, United States of America
Posts: 3,428
#2: Oct 31 '07

re: generating random numbers for 1,000,000 elements


As long as you don't ask for more than INT_MAX numbers, you should be fine.
Moderator
 
Join Date: Mar 2007
Location: North Bend Washington USA
Posts: 5,370
#3: Oct 31 '07

re: generating random numbers for 1,000,000 elements


Your array of random numbers is on the stack. You might find that you crash. If so, create your array on the heap.
Newbie
 
Join Date: Oct 2007
Location: Chicago
Posts: 9
#4: Oct 31 '07

re: generating random numbers for 1,000,000 elements


Quote:

Originally Posted by weaknessforcats

Your array of random numbers is on the stack. You might find that you crash. If so, create your array on the heap.


How do i create it on the heap?
RRick's Avatar
Expert
 
Join Date: Feb 2007
Posts: 430
#5: Nov 1 '07

re: generating random numbers for 1,000,000 elements


Since num is the number of entries, to create an int array of num entries:
Expand|Select|Wrap|Line Numbers
  1. int *iarray = new int[ num];
  2.  
  3. //  Also, what you new, you must delete
  4. delete [] iarray;
  5.  
Its not a good idea to multiply the random number, because the set of random numbers can cover all positive values of int. Line #11, might cause an integer overflow. Once that happens, your random number sequence might have repeat values.
Reply