I am getting a bad_alloc thrown when I run the executable generated from this code. I do not know why it's being thrown (I can guess it's coming from that new statement)
#include <iostream>
#include <chrono>
#include <cmath>
using namespace std;
void gen_numbers(long int numbers[], long int how_many)
{
for (int i = 0; i < how_many; i++)
{
numbers[i] = i;
}
}
bool is_prime(long int n)
{
if(n < 2)
return false;
for(int i=2; i<=sqrt(n); i++)
{
if(n % i == 0)
return false;
}
return true;
}
int count_prime_serial(long int numbers[], long int how_many)
{
int count = 0;
for(int i=0; i<how_many; i++)
{
if(is_prime(numbers[i]))
count++;
}
return count;
}
int main(){
long int n = 1000000000;
long int* numbers = new long int[n];
gen_numbers(numbers, n);
auto start = chrono::steady_clock::now();
int count = count_prime_serial(numbers, n);
auto end = chrono::steady_clock::now();
double compute_time = chrono::duration<double>(end - start).count();
cout<<"Total number of primes = "<<count<<endl;
cout<<"Total computation time = "<<compute_time<<endl;
return 0;
}
Is there any solution to stop getting this error during runtime?
I've tried compiling and running the exact same code on another machine and it ran just fine, this is why I am confused.
I have written a cpp code for array rotation and the file handling part is a bit tricky for me.
The code itself is correct but even though the files are in the same directory as the code it is not working for some reason
#include <math.h>
#include <algorithm>
#include <bits/stdc++.h>
#include <iostream>
#include <fstream>
using namespace std;
int ar[100];
// #define crap ios_base::sync_with_stdio(false);cin.tie(NULL);
int gcd(int a, int b)
{
if (b == 0)
return a;
else
return gcd(b, a % b);
}
void leftRotate(int arr[], int d, int n)
{
d = d % n;
int g_c_d = gcd(d, n);
for (int i = 0; i < g_c_d; i++) {
int temp = arr[i];
int j = i;
while (1) {
int k = j + d;
if (k >= n)
k = k - n;
if (k == i)
break;
arr[j] = arr[k];
j = k;
}
arr[j] = temp;
}
}
//int *func(int m)
//{
// int *p;
// p=new int[m];
// return (p);
//}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
// crap;
int n,d;
cin>>n>>d;
// ar=func(n);
// cout<<sizeof(ar);
for (int i=0;i<n;i++)
{
cin>>ar[i];
}
leftRotate(ar, d, n);
for (int i = 0; i < n; i++)
cout << ar[i] << " ";
return 0;
}
The code itself is working and returning correct output in the terminal but I cant seem to find the issue here
I have tried without file handling and it was giving a return value 3221225620 at the terminal
sample input is:
5 2
1 2 3 4 5
here shows a possible error:
3221225620 (0xC0000094): Zero Division Error
means that a divisor in your code could sometime be zero.
as for your code(line 20: d = d % n;), when your n is 0, the output will show return value 3221225620
so please check your data in "input.txt"
i am a beginner to c++ but i wouldn't have asked this question if i didnt spend hours on it.
The code is about finding primes between two numbers in the most efficient way where maximum limit is 10^9.
The following code gives me runtime error but i have no idea why.. help
#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
long int prime[32000];
bool isprime(long int a){
for(long int i = 3; i <= 32000; i+=2){
if(a%i == 0){
return false;
}
}
return true;
}
void generateprimes(){
long int a = 0;
for(long int i = 3; i < 31623 ; i+=2){
if(isprime(i)){
prime[a] = i;
a++;
}
}
}
bool newisprime(long int a){
long int x =0;
for(long int i = prime[x]; i <= sqrt(a); i = prime[++x]){
if(a%i == 0){
return false;
}
}
return true;
}
void generateprimes_inbetween(long int n,long int m){
if(n%2 == 0){
++n;
}
if(n == 1){
printf("2\n");
n = 3;
}
for(long int i = n; i <= m ; i+=2){
if(newisprime(i)){
printf("%d\n",i);
}
}
}
int main() {
long int a,b,c;
scanf("%ld",&a);
generateprimes();
for(long int i = 0; i < a ; i++){
scanf("%ld %ld",&b,&c);
generateprimes_inbetween(b,c);
printf("\n");
}
return 0;
}
In isprime() you loop through ALL numbers in your array prime[]. But at startup, as it's global data, most of them will be 0, so that a%i will result in a fatal divide by 0.
You have somewhere to keep track of the numer of primes that you've stored in your array and only test against the primes that you've stored there.
Supposing that it's homework and you're not allowed to use vectors, you could do it as follows:
const size_t max_primes = 32000; // avoid hard coded values
unsigned long prime[max_primes] {2, 3}; // prefilled values
size_t nprimes = 2; // number of primes in the array
bool isprime(unsigned long a){
for(size_t i = 0; i < nprimes; i++){
if(a%prime[i] == 0)
return false;
}
return true;
}
void generateprimes(){
nprimes = 2;
for(unsigned long i = 3; nprimes<max_primes && i < ULONG_MAX; i += 2){
if(isprime(i)){
prime[nprimes] = i;
nprimes++;
}
}
}
bool newisprime(unsigned long a){
size_t x = 0;
for(unsigned long i = prime[x]; i <= sqrt(a) && x<nprimes; i = prime[++x]){
if(a%i == 0)
return false;
}
if(x == nprimes) {
cout << "Attention: Reaching end of prime table !!" << endl;
}
return true;
}
Some remarks:
for the index, it's safer to use the unsigned type size_t.
make sure that whenever you use an index, it remains within the bounds
as you work with positive numbers, it could make sense to use unsigned long
I am running this pthread-c++ program (gauss elimination) on my laptop to measure its runtime.
The program runs about 10 seconds in real but my output shows about 20 seconds. What is wrong with this program?
I used
g++ -pthread main.c
./a.out 32 2048
to run
#include <stdio.h>
#include <stdlib.h>
#include <ctime>
#include <cstdlib>
#include <pthread.h>
#include <iostream>
typedef float Type;
void mat_rand (Type**, int, int);
Type** mat_aloc (int, int);
void mat_free (Type**);
void mat_print (Type**, int, int);
void* eliminate(void*);
unsigned int n, max_threads, active_threads, thread_length;
Type** A;
int current_row;
struct args
{
int start;
int end;
};
typedef struct args argument;
void *print_message_function( void *ptr );
int main(int argc, char *argv[])
{
if (argc < 3)
{
printf ("Error!. Please Enter The Matrix Dimension and No. of Threads!\n");
return 0;
} else
{
n = atoi(argv[2]);
max_threads = atoi(argv[1]);
if (n > 4096)
{
printf ("The maximum allowed size is 4096!\n");
return 0;
}
if (max_threads > 32)
{
printf ("The maximum allowed Threads Count is 32!\n");
return 0;
}
}
A = mat_aloc(n , n+1);
mat_rand (A, n, n+1);
//mat_print (A, n, n+1);
std::clock_t start;
double exe_time;
start = std::clock();
pthread_attr_t attr;
pthread_attr_init(&attr);
argument* thread_args = new argument[max_threads];
pthread_t* thread = new pthread_t[max_threads];
for (int i=0; i<n-1; i++)
{
current_row = i;
if (max_threads >= n-i)
active_threads = n-i-1;
else
active_threads = max_threads;
thread_length = (n-i-1)/active_threads;
for (int j=0; j<active_threads-1; j++)
{
thread_args[j].start = i+1+j*thread_length;
thread_args[j].end = i+1+(j+1)*thread_length;
pthread_create( &thread[j], &attr, eliminate, (void*) &thread_args[j]);
}
thread_args[active_threads-1].start = i+1+(active_threads-1)*thread_length;
thread_args[active_threads-1].end = n-1;
pthread_create(&thread[active_threads-1], &attr, eliminate, (void*) &thread_args[active_threads-1]);
for (int j=0; j<active_threads; j++)
{
pthread_join(thread[j], NULL);
}
}
exe_time = (clock() - start) / (double) CLOCKS_PER_SEC;
printf("Execution time for Matrix of size %i: %f\n", n, exe_time);
//mat_print (A, n, n+1);
return 0;
}
void* eliminate(void* arg)
{
Type k, row_constant;
argument* info = (argument*) arg;
row_constant = A[current_row][current_row];
for (int i=info->start; i<=info->end; i++)
{
k = A[i][current_row] / row_constant;
A[i][current_row] = 0;
for (int j=current_row+1; j<n+1; j++)
{
A[i][j] -= k*A[current_row][j];
}
}
}
// matrix random values
void mat_rand (Type** matrix, int row, int column)
{
for (int i=0; i<row; i++)
for (int j=0; j<column; j++)
{
matrix[i][j] = (float)(1) + ((float)rand()/(float)RAND_MAX)*256;
}
}
// allocates a 2d matrix
Type** mat_aloc (int row, int column)
{
Type* temp = new Type [row*column];
if (temp == NULL)
{
delete [] temp;
return 0;
}
Type** mat = new Type* [row];
if (temp == NULL)
{
delete [] mat;
return 0;
}
for (int i=0; i<row; i++)
{
mat[i] = temp + i*column;
}
return mat;
}
// free memory of matrix
void mat_free (Type** matrix)
{
delete[] (*matrix);
delete[] matrix;
}
// print matrix
void mat_print (Type** matrix, int row, int column)
{
for (int i=0; i<row; i++)
{
for (int j=0; j<column; j++)
{
std::cout<< matrix[i][j] << "\t\t";
}
printf("\n");
}
printf(".................\n");
}
clock reports CPU time used. If you have 2 CPUs and run a thread on each one for 10 seconds, clock will report 20 seconds.
Here is some working code that implements a modified version of the Quicksort algorithm that uses Insertion Sort for array size n > 8. My test array isn't sorting exactly right, and I think it must be with my implementation of Insertionsort and Insert.
The general form of the recursive Insertionsort algorithm is:
void Insertionsort(int S[], int n)
{
if(n>1)
Insertionsort(S,n-1);
Insert(S,n-1);
}
void Insert(int *S, int k)
{
int key = S[k];
int j = k-1;
while(j>=0 && S[j] > key)
{
S[j+1] = S[j];
j--;
}
S[j+1] = key;
}
Here is my complete working code that does not sort quite exactly right:
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int comparisons = 0;
int compare_qs_m3_ins[12];
// Function prototypes
int partition(int *S,int l, int u);
void exchange(int list[], int p, int q);
void Insert(int S[], int k);
void Insertionsort(int S[], int low, int hi);
void Quicksort_Insert_M3(int S[], int n, int p, int r);
int main()
{
srand (time(NULL));
// Declare all arrays used for testing
int S1_500[500];
int S2_500[500];
int S3_500[500];
int S1_300[300];
int S2_300[300];
int S3_300[300];
int S1_100[100];
int S2_100[100];
int S3_100[100];
int S1_8[8];
int S2_8[8];
int S3_8[8];
// Fill arrays with random integers
for(int i=0; i<500; i++)
{
S1_500[i] = rand()%1000;
S2_500[i] = rand()%1000;
S3_500[i] = rand()%1000;
}
for(int i=0; i<300; i++)
{
S1_300[i] = rand()%1000;
S2_300[i] = rand()%1000;
S3_300[i] = rand()%1000;
}
for(int i=0; i<100; i++)
{
S1_100[i] = rand()%500;
S2_100[i] = rand()%500;
S3_100[i] = rand()%500;
}
for(int i=0; i<8; i++)
{
S1_8[i] = rand()%100;
S2_8[i] = rand()%100;
S3_8[i] = rand()%100;
}
Quicksort_Insert_M3(S1_500,500,0,499);
compare_qs_m3_ins[0] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S2_500,500,0,499);
compare_qs_m3_ins[1] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S3_500,500,0,499);
compare_qs_m3_ins[2] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S1_300,300,0,299);
compare_qs_m3_ins[3] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S2_300,300,0,299);
compare_qs_m3_ins[4] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S3_300,300,0,299);
compare_qs_m3_ins[5] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S1_100,100,0,99);
compare_qs_m3_ins[6] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S2_100,100,0,99);
compare_qs_m3_ins[7] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S3_100,100,0,99);
compare_qs_m3_ins[8] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S1_8,8,0,7);
compare_qs_m3_ins[9] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S2_8,8,0,7);
compare_qs_m3_ins[10] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S3_8,8,0,7);
compare_qs_m3_ins[11] = comparisons;
comparisons = 0;
//for(int i=0; i<12; i++)
//cout << compare_qs_m3_ins[i] << endl;
for(int i=0;i<499;i++)
cout << S1_500[i] << endl;
}
int partition(int *S,int l, int u)
{
int x = S[l];
int j = l;
for(int i=l+1; i<=u; i++)
{
comparisons++;
if(S[i] < x)
{
j++;
swap(S[i],S[j]);
}
}
int p = j;
swap(S[l],S[p]);
return p;
}
void swap(int &val1, int &val2)
{
int temp = val1;
val1 = val2;
val2 = temp;
}
void exchange(int list[], int p, int q)
{
int temp = list[p];
list[p] = list[q];
list[q] = temp;
}
int Sort3(int list[], int p, int r)
{
int median = (p + r) / 2;
comparisons++;
if(list[p] <= list[median])
{
comparisons++;
if(list[median]>list[r])
{
comparisons++;
if(list[p]<list[r])
{
int temp = list[p];
list[p] = list[r];
list[r] = list[median];
list[median] = temp;
}
else
{
exchange(list,median,r);
}
}
else
;
}
else
{
comparisons++;
if(list[p] > list[r])
{
comparisons++;
if(list[median] < list[r])
{
int temp = list[p];
list[p] = list[median];
list[median] = list[r];
list[r] = temp;
}
else
{
exchange(list,p,r);
}
}
else
{
exchange(list,p,median);
}
}
return list[r];
}
void Insert(int *S, int k)
{
int key = S[k];
int j = k-1;
while(j>=0 && S[j] > key)
{
S[j+1] = S[j];
j--;
comparisons++;
}
comparisons++;
S[j+1] = key;
}
void Insertionsort(int S[], int low, int hi)
{
if((hi-low)+1>1)
Insertionsort(S,low+1,hi);
Insert(S,hi-low);
}
void Quicksort_Insert_M3(int S[], int n, int low, int hi)
{
if((hi-low)<=8)
Insertionsort(S,low,hi);
else
{
if(low < hi)
{
if((low+1) == hi)
{
comparisons++;
if(S[low] > S[hi])
swap(S[low],S[hi]);
}
else
{
Sort3(S,low,hi);
if((low+2)<hi)
{
swap(S[low+1],S[(low+hi)/2]);
int q = partition(S, low+1, hi-1);
Quicksort_Insert_M3(S, n, low, q-1);
Quicksort_Insert_M3(S, n, q+1, hi);
}
}
}
}
}
The function supposed to sort three array elements in ascending order doesn't:
int Sort3(int list[], int p, int r)
{
called only for p + 2 <= r, so
int median = (p + r) / 2;
p < median < r here. Let a = list[p], b = list[median] and c = list[r].
comparisons++;
if(list[p] <= list[median])
{
comparisons++;
if(list[median]>list[r])
{
comparisons++;
if(list[p]<list[r])
{
So here we have a <= b, c < b and a < c, together a < c < b
int temp = list[p];
list[p] = list[r];
list[r] = list[median];
list[median] = temp;
but you place them in order c, a, b. Probably you intended to use if (list[r] < list[p]) there.
}
else
c <= a <= b
{
exchange(list,median,r);
so that arranges them in order a, c, b.
}
}
else
;
}
else
Here, b < a.
{
comparisons++;
if(list[p] > list[r])
{
c < a
comparisons++;
if(list[median] < list[r])
{
Then b < c < a
int temp = list[p];
list[p] = list[median];
list[median] = list[r];
list[r] = temp;
Yup, that's correct.
}
else
c <= b < a
{
exchange(list,p,r);
}
Okedoke.
}
else
{
b < a <= c
exchange(list,p,median);
Okay.
}
}
return list[r];
}
Why does this function return anything? You don't use the return value anyway.
"The general form of the recursive Insertionsort algorithm is" - if you need to have a head-recursive algorithm, yes, otherwise a better version is:
void Insertionsort(int S[], int i, int n)
{
Insert(S, i, n);
if(i < n)
Insertionsort(S, i+1, n);
}
which is much more understandable. Also, you might as well have put the body of Insert into Insertionsort.
I'm not going to try and figure out your overly complicated version of quicksort. A decent quicksort is around 20 lines or less (like this - www.algolist.net/Algorithms/Sorting/Quicksort) (and add another 10 or less for insertion sort). I suggest getting a better understanding by looking at another implementation and rewriting yours.
I believe this could've been asked as an extension of your previous question.