My task is to implement just the merge function of merge sort algorithm.My idea is to create an auxilliary array to store the sorted values.I have mainted 2 pointers,one for left sorted array and other for right sorted array.
I am having difficulty in figuring out why am I getting segmentation fault?
void merge(int arr[], int l, int m, int r)
{
int temp[r-l+1];int count=0;
int *ptr1=(int*) malloc(sizeof(int));
int * ptr2=(int*) malloc(sizeof(int));
ptr1=&arr[l];
ptr2=&arr[m+1];
while(ptr1!=(&arr[m+1]) && ptr2!=NULL)
{
if(*ptr1>=*ptr2)
{
temp[++count]=*ptr2;
ptr2++;
}
else
{
temp[++count]=*ptr1;
ptr1++;
}
}
if(ptr1==&arr[m+1])
{
while(ptr2)
{
temp[++count]=*ptr2;
ptr2++;
}
}
if(ptr2==NULL)
{
while(ptr1!=&arr[m+1])
{
temp[++count]=*ptr1;
ptr1++;
}
}
for(int i=0;i<r-l+1;i++)
{
arr[i]=temp[i];
}
}
Input:
2
5
4 1 3 9 7
10
10 9 8 7 6 5 4 3 2 1
Expected Output:
1 3 4 7 9
1 2 3 4 5 6 7 8 9 10
My Output:Segmentation fault
First of all, these lines for malloc are not necessary
int *ptr1=(int*) malloc(sizeof(int));
int * ptr2=(int*) malloc(sizeof(int));
ptr1=&arr[l];
ptr2=&arr[m+1];
and can be changed to
int *ptr1=&arr[l];
int * ptr2=&arr[m+1];
The other problem is that the test for NULL for ptr2 does not work since the address past the last element is not NULL.
Related
Okay so I'm trying find the factors of a number in time better than O(sqrt(n)) which made me look up the Sieve approach. Now I'm trying to find the factors of that number that is less than a given n(n<=number). Here's what I tried:
#include <bits/stdc++.h>
#define lli long long int
using namespace std;
const int Max=1000001;
lli prime[Max];
void sieveGen()
{
prime[0]=0;
prime[1]=1;
for(lli i=2;i<Max;i++)
{
prime[i]=i;
}
for(lli i=4;i<Max;i+=2)
{
prime[i]=2;
}
for(lli i=3;i<Max;i++)
{
if(prime[i]==i)
{
if(i*i>Max)
{
break;
}
for(lli j=i*i;j<Max;j+=i)
{
if(prime[j]==j)
{
prime[j]=i;
}
}
}
}
}
lli count_factors(lli num,lli i)
{
if(i==2)
return 1;
if(i==3)
{
if(num%2==0)
{
return 2;
}
else
{
return 1;
}
}
lli ans=1;
lli count=1;
lli first_prime=prime[num];
lli second_prime=num/prime[num];
while(second_prime!=1&&firstprime<i)
{
if(prime[second_prime]==first_prime)
{
count++;
}
else
{
first_prime=prime[second_prime];
ans=ans*(count+1);
count=1;
}
second_prime=second_prime/prime[second_prime];
if(first_prime<i)
{
ans=ans*(count+1);
}
}
return ans;
}
int main() {
sieveGen();
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin>>t;
while(t--)
{
lli N,M,res=0;
cin>>N>>M;
if(M==1)
{
res+=N-1;
}
else
{
for(lli i=2;i<=N;i++)
{
lli num=M-(M%i);
if(num>0)
{
cout<<i<<"."<<count_factors(num,i)<<"\n";
res+=count_factors(num,i);
}
else
{
res+=(i-1);
}
}
}
cout<<res<<"\n";
}
return 0;
}
Here, I want to find the number of factors of num that are less than i.
This is working fine for any prime i but fails for some other numbers like 6.
Any help is highly appreciated.
SoE for number for dividers is like this:
init SoE[n] array
so allocate and clear with 0 the 1D array of integers of size n where n-1 is the max value you want to query.
for each number i from 2 to n-1 compute SoE
so simply increment all SoE[j] where j=i,2*i,3*i,4*i,...
now SoE[x] holds the number of dividers of x
its not accounting 1 but its accounting i so if you want not to just use decremented value.
Your for n=13 example would SoE look like this:
x | SoE[x]
--+-------
1 | 0
2 | 1
3 | 1
4 | 2
5 | 1
6 | 3
7 | 1
8 | 3
9 | 2
10| 3
11| 1
12| 5
so for x=12 the SoE[12]=5 and if you do not want to account x itself use 5-1=4 dividers (2,3,4,6).
In case you also want the dividers itself (not just their count) then you can store the list of all numbers that divide instead of count in the SoE
x | SoE[x]
--+-------
1 |
2 | 2
3 | 3
4 | 2,4
5 | 5
6 | 2,3,6
7 | 7
8 | 2,4,8
9 | 3,9
10| 2,5,10
11| 11
12| 2,3,4,6,12
again you can ignore the last element in SoE[x] list if you do not want to account x itself.
Prime decomposition is almost the same as this except you use only primes as i in the bullet #2.
I have started studying C++ after some years in C# and other languages. I am facing the class arguments (constructors, inheritance, copy etc) and I was trying to write a bad sample code. Below is a sample class (.h and .cpp):
#ifndef SAMPLE_H
#define SAMPLE_H
#include <iostream>
class Sample
{
public:
Sample();
//Sample(const Sample& s);
virtual ~Sample();
int *s_array;
protected:
private:
};
void print(const Sample *s);
#endif // SAMPLE_H
Sample::Sample()
{
std::cout<<"create sample\n";
s_array=new int[10];
std::cout<<"alloc memory 10 int array\n";
for(int i=0; i<10; ++i)
{
s_array[i]=i;
}
}
Sample::~Sample()
{
//dtor
std::cout<<"Dealloc memory 10 int array\n";
delete [] s_array;
std::cout<<"destroy sample\n";
}
void print(const Sample *s)
{
std::cout<<s<<" "<<s->s_array<<'\n';
for(int i=0; i<10; ++i)
{
std::cout<<s->s_array[i]<<" ";
}
std::cout<<"\n\n";
}
Then in main
#include <iostream>
#include "Sample.h"
using namespace std;
int main()
{
cout<<endl<<"Let's try the Copy const WRONG.... "<<endl;
Sample *s1=new Sample();
print(s1);
Sample s2(*s1);
cout<<endl<<"What is s2 ??? "<<endl;
print(&s2);
delete s1;
cout<<endl<<"What is s2 NOW after s1 delete??? "<<endl;
print(&s2);
return 0;
}
I wanted to test the dangers of NOT to use the copy constr and i expected to see after the deletion of s1 a totally 'dirty' array (i.e., 10 random values or even a crash)
This is the output I gain (Win 10 pro, IDE CodeBlock, GNU Gcc compiler):
Let's try the Copy const WRONG....
create sample
alloc memory 10 int array
0x1ba110 0x1b6e48
0 1 2 3 4 5 6 7 8 9
What is s2 ???
0x6efdf0 0x1b6e48
0 1 2 3 4 5 6 7 8 9
Dealloc memory 10 int array
destroy sample
What is s2 NOW after s1 delete???
0x6efdf0 0x1b6e48
1812296 1769664 2 3 4 5 6 7 8 9
Dealloc memory 10 int array
destroy sample
Why only the first two items of s_array are 'dirty' and the remaining 8 are good? Why the deletion of object s1 does not free the whole memory pointed by s2?
Thanx in advance
Diego
I'm trying to work on a sub-problem of an larger algorithm which I am really struggling on!
The Problem
If I had a array of numbers (say A), how can I efficiently list all the numbers that can be made by multiplying the numbers together (which can be used as many times as you want) and is less than another number (say x).
For example, let's say I had A = [7, 11, 13] and x was 1010, the answers would be:
- 7 = 7
- 11 = 11
- 13 = 13
- 7*7 = 49
- 7*11 = 77
- 7*13 = 91
- 11*11 = 121
- 11*13 = 143
- 13*13 = 169
- 7*7*7 = 343
- 7*7*11 = 539
- 7*7*13 = 637
- 7*11*11 = 847
- 7*11*13 = 1001
I tried my best not to miss any (but feel free to edit if I have)!
I can tell this is probably some type of recursion but am really struggling on this one!
Optional
A naive solution will also be nice (that's how much I'm struggling).
Running time is also optional.
UPDATE
All numbers in A are all the prime numbers (except 1, 2, 3, 5) got from the sieve of eratosthenes.
UPDATE 2
A is also sorted
UPDATE 3
All numbers in A is under the limit
UPDATE 4
The solution does NOT need to be recursion. That was just an idea I had. And Java or Pseudo code more preferable!
I'd go with using a queue. The algorithm I have in mind would be something like the following (in pseudocode):
multiplyUntil(A, X)
{
queue q = A.toQueue();
result;
while(!q.isEmpty())
{
element = q.pop();
result.add(element); // only if the initial elements are guaranteed to be < X otherwise you should add other checks
for(int i = 0; i < A.length; i++)
{
product = element * A[i];
// A is sorted so if this product is >= X the following will also be >= X
if(product >= X)
{
// get out of the inner cycle
break;
}
q.add(product);
}
}
return result;
}
Let me know if something is unclear.
P.S: Keep in mind that the result is not guaranteed to be sorted. If you want the result to be sorted you could use a heap instead of a queue or sort the result in the end of the computation.
Here's solution on Java along with comments. It's pretty straightforward to translate it to other language.
// numbers is original numbers like {7, 11, 13}, not modified
// offset is the offset of the currently processed number (0 = first)
// limit is the maximal allowed product
// current array is the current combination, each element denotes
// the number of times given number is used. E. g. {1, 2, 0} = 7*11*11
private static void getProducts(int[] numbers, int offset, int limit, int[] current) {
if(offset == numbers.length) {
// all numbers proceed: output the current combination
int product = 1;
StringBuilder res = new StringBuilder();
for(int i=0; i<offset; i++) {
for(int j = 0; j<current[i]; j++) {
if(res.length() > 0) res.append(" * ");
res.append(numbers[i]);
product *= numbers[i];
}
}
// instead of printing you may copy the result to some collection
if(product != 1)
System.out.println(" - "+res+" = "+product);
return;
}
int n = numbers[offset];
int count = 0;
while(limit >= 1) {
current[offset] = count;
getProducts(numbers, offset+1, limit, current);
count++;
// here the main trick: we reduce limit for the subsequent recursive calls
// note that in Java it's integer division
limit/=n;
}
}
// Main method to launch
public static void getProducts(int[] numbers, int limit) {
getProducts(numbers, 0, limit, new int[numbers.length]);
}
Usage:
public static void main(String[] args) {
getProducts(new int[] {7, 11, 13}, 1010);
}
Output:
- 13 = 13
- 13 * 13 = 169
- 11 = 11
- 11 * 13 = 143
- 11 * 11 = 121
- 7 = 7
- 7 * 13 = 91
- 7 * 11 = 77
- 7 * 11 * 13 = 1001
- 7 * 11 * 11 = 847
- 7 * 7 = 49
- 7 * 7 * 13 = 637
- 7 * 7 * 11 = 539
- 7 * 7 * 7 = 343
The resulting products are sorted in different way, but I guess sorting is not a big problem.
Here is my solution in C++. I use a recursive function. The principle is:
the recursive function is given a limit, a current which is a composite and a range of primes [start, end(
it will output all combination of powers of the primes in the given range, multiplied by the current composite
At each step, the function takes the first prime p from the range, and compute all its powers. It then multiplies current by the p as long as the product, cp is under the limit.
We use the fact the array is sorted by leaving as soon as cp is above the limit.
Due to the way we compute the numbers they won't be sorted. But it is easy to add this as a final step once you collected the numbers (in which case ou would use a back_inserter output iterator instead of an ostream_iterator, and do a sort on the collection vector)
#include <algorithm>
#include <iostream>
#include <iterator>
using namespace std;
template <class It, class Out>
void f(int limit, int current, It start, It end, Out out) {
// terminal condition
if(start == end) {
if(current != 1)
*(out++) = current;
return;
}
// Output all numbers where current prime is a factor
// starts at p^0 until p^n where p^n > limit
int p = *start;
for(int cp = current; cp < limit; cp *= p) {
f(limit, cp, start+1, end, out);
}
}
int main(int argc, char* argv[]) {
int const N = 1010;
vector<int> primes{7, 11, 13};
f(N, 1, begin(primes), end(primes), ostream_iterator<int>(cout, "\n"));
}
I had a test right now and this was one of the questions:
Input
The places to visit in the labyrinth are numbered from 1 to n. The entry and
the exit correspond to number 1 and number n, respectively; the remaining
numbers correspond to crossings. Note that there are no dead ends and
there is no more than one connection linking a pair of crossings.
For each test case, the first line gives n and the number of connections
between crossings (m). Then, in each of the following m lines, you find a pair
of integers corresponding to the connection between two crossings.
Output
For each test case, your implementation should output one single line
containing "Found!", if it is possible to reach the exit by visiting every
crossing once or "Damn!", otherwise. Other test cases may follow.
Constraints
m < 32
n < 21
Example input:
8 13
1 2
1 3
2 3
2 4
3 4
3 5
4 5
4 6
5 6
5 7
6 7
6 8
7 8
8 8
1 2
1 3
2 4
3 5
4 6
5 7
6 8
7 8
Example output:
Found!
Damn!
I solved the problem using a sort of DFS algorithm but i have a few questions.
Using DFS algorithm, I implemented a recursive function that starts in the given node and tries to visit every node once and the last node must be the exit node. I don't have the full code right now but but it was something like this:
findPath(int current node, int numVisitedNodes, int *visited){
int *tmpVisited = copyArray(visited); //copies the visited array to tmpVisited
//DFS algo here
}
Every recursive call it copies the visited nodes array. I'm doing this because when it finds an invalid path and the recursion goes back to the origin, it can still go because no one overwrote the visited nodes list.
Is there any better way to do this?
How would you solve it? (you can provide code if you want)
Read the crossing
if start or end of the crossing belongs to a reachable set, add both to that set else create a new reachable set.
When input has finished, check if any of the reachable sets contains
both entrance and exit points
HashSet operations complexity is O(1). If every crossing are distinct, complexity is O(n^2),which is the worst case complexity of this algorithm. Space complexity is O(n), there is no recursion so there is no recursion overhead of memory.
Roughly speaking, every node is visited only once.
Java code using valid reachable sets is as follows.
public class ZeManel {
public static void main(String[] args) {
Integer[][] input = {{1,2},{2,3},{4,6}};
zeManel(input);
}
public static void zeManel(Integer[][] input){
List<Set<Integer>> paths = new ArrayList<Set<Integer>>();
int max = 0;
for(int i = 0;i < input.length;i++) {
max = input[i][0] > max ? input[i][0] : max;
max = input[i][1] > max ? input[i][1] : max;
boolean inPaths = false;
for (Set<Integer> set : paths) {
if(set.contains(input[i][0]) || set.contains(input[i][1])) {
set.add(input[i][0]);
set.add(input[i][1]);
inPaths = true;
break;
}
}
if(!inPaths) {
Set<Integer> path = new HashSet<Integer>();
path.add(input[i][0]);
path.add(input[i][1]);
paths.add(path);
}
}
for (Set<Integer> path : paths) {
if(path.contains(1) && path.contains(max)) {
System.out.println("Found!");
return;
}
}
System.out.println("Damn!");
}
}
This was my implementation during the test:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
# define N 21
# define M 32
int i;
int adj[N][N];
int count = 0;
int findPath(int numNodes, int currentNode, int depth, int *visited){
visited[currentNode] = 1;
if(currentNode == numNodes - 1 && depth == numNodes){
return 1;
}
if(depth > numNodes)
return -1;
int r = -1;
if(depth < numNodes){
count++;
int *tmp = (int*) malloc(numNodes*sizeof(int));
for(i = 0; i < numNodes; i++)
tmp[i] = visited[i];
for(i = 0; i < numNodes; i++){
if(adj[currentNode][i] == 1 && tmp[i] == 0 && r == -1){
if(findPath(numNodes, i, depth + 1, tmp) == 1)
r = 1;
}
}
free(tmp);
}
return r;
}
int main(){
int numLigacoes, a, b, numNodes;
int *visited;
while (scanf("%d %d", &numNodes, &numLigacoes) != EOF){
visited = (int*) malloc(numNodes*sizeof(int));
count = 0;
memset(adj, 0, N*N*sizeof(int));
memset(visited, 0, numNodes*sizeof(int));
for (i = 0; i < numLigacoes; i++){
scanf("%d %d", &a, &b);
adj[a - 1][b - 1] = 1;
adj[b - 1][a - 1] = 1;
}
if(findPath(numNodes, 0, 1, visited) == 1)
printf("Found! (%d)\n", count);
else
printf("Damn! (%d)\n", count);
free(visited);
}
return 0;
}
What do you think about that?
Thank you ,
i am trying to solve a project euler problem it wants me to print the sum of
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
this is formed by starting with the number 1 and moving to the right in a clockwise direction for a 5 by 5 matrix but i am in trouble writing a code for the spiral matrix !!
It is Highly recommended to do project Euler problems on your own and ask for help if you are really stuck
here is how i will write a code in c to print a spiral as suggested in the question
#include<stdio.h>
main()
{
int i,j,nq=9;//nq is a odd number which represents the order of the matrix
int lim=(int)nq/2,cnt=2;
int a[nq][nq];
for(i=0;i<nq;i++){
for(j=0;j<nq;j++)
a[i][j]=0;
}
a[lim][lim]=1;
a[lim][lim+1]=2;
int i1=lim,j1=lim+1;i=lim,j=lim;
while(1){
if(cnt>(nq*nq))
break;
cnt++;
if(i==i1)
{ j=j1;
if(i<=lim)
{
i=i1;
if(a[i1+1][j1]==0)
a[++i1][j]=cnt;
else
a[i1][++j1]=cnt;
}
else
{ i=i1;
if(a[i1-1][j1]==0)
a[--i1][j1]=cnt;
else
a[i1][--j1]=cnt;
}
}
else
{ i=i1;
if(j<lim)
{
j=j1;
if(a[i1][j+1]==0)
a[i1][++j1]=cnt;
else
a[--i1][j1]=cnt;
}
else
{ j=j1;
if(a[i1][j1-1]==0)
a[i1][--j1]=cnt;
else
a[++i1][j1]=cnt;
}
}
}
for(i=0;i<nq;i++){
for(j=0;j<nq;j++)
printf(" %d ",a[i][j]);
printf("\n");
}
}
I Googled your question http://projecteuler.net/problem=28 this can also be solved by taking advantage of its mathematical nature note that
Top right corner is n^2
and other corners can be shown to be n^2-2n+2 ,n^2-n+1, and n^2-3n+3. you just need to sum those corners which comes to be
= 4*n^2 - 6*n + 6
hence the final answer can be calculated by iterating over every second number from 1001 to 3
long int sum(int n){
long int sum=1;
while(n>1){
sum=sum+4*n*n-6*n+6;
n=n-2;
}
return sum;
}
I dont know whether you actually want to print the spiral but see below for my solution for #28 written in Python 2.7.
l = [1]
def corners(step,l):
counter = 0
while counter < 4:
l.append(max(l)+step)
counter +=1
return l
step = 2
while step < 1001:
l = corners(step, l)
step += 2
print sum(l)
void printSpiral(int A[3][5],int m, int n)
{
int T=0; int B=m-1; int L=0; int R=n-1;
int dir=0;
int i =0; int j=0; int k=0; int l=0;
while(T<=B && L<=R)
{
//printf("dir %d ",dir);
if(dir == 0)
{
for( i=L;i<=R;i++)
{
printf("%d ",A[T][i]);
//printf("\n");
}
T++;
dir=1;
}
else if(dir == 1)
{
// printf("%d R ",R);
for( j=T;j<= B;j++)
{
printf("%d ",A[j][R]);
//printf("\n");
//printf("dir1");
}
dir=2;
R--;
}
else if(dir == 2)
{
for(k=R;k>= L;k--)
{
printf("%d ",A[B][k]);
}
dir=3;
B--;
}
else if(dir == 3)
{
for( l=B;l>= T;l--)
{
printf("%d ",A[l][L]);
}
L++;
dir=0;
}
}
}