Compute Absolute values of N integer combinations Combinations - c++

For a N number (a..N) I am finding set of all combinations in the following way:
void create_print_combinations(int *t, int x, int n) {
if(x == 0) {
char p [2 * r + 2];
memset (p, 0, 2 * r +2);
for (int j=c;j>0;j--)
if(j == c)
sprintf(p, "%d", t[j]);
else
sprintf(p, "%s,%d", p,t[j]);
print_combi(p);
} else {
for (int i= n; i < r; i++) {
t[x] = a[i];
create_print_combinations(t, x-1, i+1);
}
}
}
So a call to function like:
int main() {
unsigned long int start=0, end=0;
printf ("\nEnter the a positive integer N:");
scanf("%d", &r);
start=time(NULL);
a = new int[r];
for (int i = 0;i<r;i++)
a[i]=i+1;
for(int j=1;j<=r;j++) {
a1 = new int[j];
c=j;
create_print_combinations(a1, c, 0);
delete[] a1;
}
end=time(NULL);
printf("Total time taken = %llu\n" , end - start);
return 0;
}
Gives me combinations like for N=4:
Enter the a positive integer N:4
Combo : [1]
Combo : [2]
Combo : [3]
Combo : [4]
Combo : [1,2]
Combo : [1,3]
Combo : [1,4]
Combo : [2,3]
Combo : [2,4]
Combo : [3,4]
Combo : [1,2,3]
Combo : [1,2,4]
Combo : [1,3,4]
Combo : [2,3,4]
Combo : [1,2,3,4]
Now my tasks is to fond the absolute values of all combinations like:
For Combo [1,2,3,4] it should be:
1+2+3+4 = abs(1+2+3+4)
1+2+3-4 = abs(1+2+3-4)
1+2-3-4 = ..
1-2-3+4 = ...
Ans so on
I am trying the below logic:
while(pos > 0)
{
for(int a=0; a < i; a++)
{
if(a==0)
sprintf(p,"%d", t[a]);
else if(a == pos)
sprintf(p,"%s%c%d",p, minus, t[a]);
else
sprintf(p,"%s%c%d",p, plus, t[a]);
}
print(p);
memset (p , 0, 2 * r +2);
pos --;
}
But I beleiev I am doing something wrong as all sets are not getting printed. I am unable to frame the logic though I feel I am near to completion. Below is my whole program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
int *a;
int *a1;
int r;
int c;
unsigned long int no =1;
int stoi(char *var)
{
int n1 = 0;
int n2 = 0;
int n3 = 0;
char sign=0;
while(*var)
{
if(isspace(*var))
{
var++;
continue;
}
while(*var >= '0' && *var <= '9')
{
n1=(n1*10) + (*var - '0');
var++;
continue;
}
if(sign == '+')
{
n2=n2+n1;
n1=0;
}
else if(sign == '-')
{
n2=n2 - n1;
n1=0;
}
if(*var == '+' || *var == '-')
{
if(sign == 0)
{
n2=n1;
n1=0;
}
sign = *var;
}
var++;
}
if(sign == 0)
return abs(n1);
return abs(n2);
}
void print(char* var)
{
printf("[Combo %llu.] %s = %d\n" , no++, var, stoi(var));
}
void print_combi(char * a)
{
int t[c];
char *x = NULL;
char *y = a;
int i=0;
while((x=strchr(y, ',')) != NULL)
{
*x = '\0';
t[i++]=atoi(y);
y=x+1;
}
t[i++]=atoi(y);
int count =0;
int loop = 0;
char p [2 * r + 2];
memset (p , 0, 2 * r +2);
char plus = '+';
char minus = '-';
for(int k=0;k<2;k++)
{
if(k==1)
{
plus = '-';
minus = '+';
}
if(i>1)
{
for(int a=0; a < i; a++)
{
if(a==0)
sprintf(p,"%d", t[a]);
else
sprintf(p,"%s%c%d",p, plus, t[a]);
}
}
else if(i==1)
{
sprintf(p,"%d", t[i-1]);
print(p);
break;
}
print(p);
memset (p , 0, 2 * r +2);
if(i==2)
continue;
if(i==3 && k ==1)
break;
int pos = i-1;
while(pos > 0)
{
for(int a=0; a < i; a++)
{
if(a==0)
sprintf(p,"%d", t[a]);
else if(a == pos)
sprintf(p,"%s%c%d",p, minus, t[a]);
else
sprintf(p,"%s%c%d",p, plus, t[a]);
}
print(p);
memset (p , 0, 2 * r +2);
pos --;
}
}
}
void create_print_combinations(int *t, int x, int n)
{
if(x == 0)
{
char p [2 * r + 2];
memset (p, 0, 2 * r +2);
for (int j=c;j>0;j--)
if(j == c)
sprintf(p, "%d", t[j]);
else
sprintf(p, "%s,%d", p,t[j]);
print_combi(p);
}
else
for (int i= n; i < r; i++)
{
t[x] = a[i];
create_print_combinations(t, x-1, i+1);
}
}
int main()
{
unsigned long int start=0, end=0;
printf ("\nEnter the a positive integer N:");
scanf("%d", &r);
start=time(NULL);
a = new int[r];
for (int i = 0;i<r;i++)
a[i]=i+1;
for(int j=1;j<=r;j++)
{
a1 = new int[j];
c=j;
create_print_combinations(a1, c, 0);
delete[] a1;
}
end=time(NULL);
printf("Total time taken = %llu\n" , end - start);
return 0;
}
As per the program logic I am computing the combinations as strings and the generating the absolute values of the expression.

There is a simpler way to what you are doing. You want to add up a vector of N integers:
[ 1*k1, 2*k2, 3*k3 ... N*kN ]
where kx = -1, 0, +1.
There are 3^N combinations of kx for x=1..N.

Some code for #SteveC's solution:
#include <iostream>
#include <sstream>
using namespace std;
void print_sum(int N, int sum_so_far, string as_a_string) {
if(N) {
ostringstream oss; oss << N;
print_sum(N-1, sum_so_far+N, as_a_string + "+" + oss.str() + " ");
print_sum(N-1, sum_so_far-N, as_a_string + "-" + oss.str() + " ");
print_sum(N-1, sum_so_far, as_a_string);
} else {
if (sum_so_far < 0) sum_so_far *= -1;
cout << as_a_string << "\t= " << sum_so_far << endl; }
}
int main() {
print_sum(4, 0, "");
}
The output begins:
+4 +3 +2 +1 = 10
+4 +3 +2 -1 = 8
+4 +3 +2 = 9
+4 +3 -2 +1 = 6
+4 +3 -2 -1 = 4
+4 +3 -2 = 5
+4 +3 +1 = 8
+4 +3 -1 = 6
# .. and so on

What you are trying to do is very similar to enumerating all combinations from "N choose 1" to "N choose N". I would suggest you search in google under the terms "Enumerate Combinations"
Here is one of the link I have found:
http://www.codeproject.com/KB/recipes/CombC.aspx

Here is a logic on how to do it. Print all the binary digits of size n-1 where n is the size (number of elements) of the respective combo. For example to do what you want to do for the combo [1,2,3,4] create all the binary combinations of 3 (n-1 = 3, here n = 4 elements). i.e.
when n = 3, the possible combinations are:
000
001
010
011
100
101
110
111
Now run your combo in a for loop and inside it whenever you find a 0 do addition and whenever you find 1 do a subtraction. For example 000 would mean 1+2+3+4 and 101 would mean 1-2+3-4.

Related

How to get the minimum XOR of a given value and the value from a query of range for a given array

Given an array A of n integers and given queries in the form of range [l , r] and a value x, find the minimum of A[i] XOR x where l <= i <= r and x will be different for different queries.
I tried solving this problem using segment trees but I am not sure what type of information I should store in them as x will be different for different queries.
0 < number of queries <= 1e4
0 < n <= 1e4
To solve this I used a std::vector as basis (not an array, or std::array), just for flexibility.
#include <algorithm>
#include <stdexcept>
#include <vector>
int get_xored_max(const std::vector<int>& values, const size_t l, const size_t r, const int xor_value)
{
// check bounds of l and r
if ((l >= values.size()) || (r >= values.size()))
{
throw std::invalid_argument("index out of bounds");
}
// todo check l < r
// create left & right iterators to create a smaller vector
// only containing the subset we're interested in.
auto left = values.begin() + l;
auto right = values.begin() + r + 1;
std::vector<int> range{ left, right };
// xor all the values in the subset
for (auto& v : range)
{
v ^= xor_value;
}
// use the standard library function for finding the iterator to the maximum
// then use the * to dereference the iterator and get the value
auto max_value = *std::max_element(range.begin(), range.end());
return max_value;
}
int main()
{
std::vector<int> values{ 1,3,5,4,2,4,7,9 };
auto max_value = get_xored_max(values, 0u, 7u, 3);
return 0;
}
Approach - Trie + Offline Processing
Time Complexity - O(N32)
Space Complexity - O(N32)
Edit:
This Approach will fail. I guess, we have to use square root decomposition instead of two pointers approach.
I have solved this problem using Trie for finding minimum xor in a range of [l,r]. I solved queries by offline processing by sorting them.
Input format:
the first line has n (no. of elements) and q (no. of queries). the second line has all n elements of the array. each subsequent line has a query and each query has 3 inputs l, r and x.
Example -
Input -
3 3
2 1 2
1 2 3
1 3 2
2 3 5
First, convert all 3 queries into queries sorted by l and r.
converted queries -
1 2 3
1 3 2
2 3 5
Key here is processing over sorted queries using two pointers approach.
#include <bits/stdc++.h>
using namespace std;
const int N = (int)2e4 + 77;
int n, q, l, r, x;
int a[N], ans[N];
vector<pair<pair<int, int>, pair<int, int>>> queries;
// Trie Implementation starts
struct node
{
int nxt[2], cnt;
void newnode()
{
memset(nxt, 0, sizeof(nxt));
cnt = 0;
}
} trie[N * 32];
int tot = 1;
void update(int x, int v)
{
int p = 1;
for (int i = 31; i >= 0; i--)
{
int id = x >> i & 1;
if (!trie[p].nxt[id])
{
trie[++tot].newnode();
trie[p].nxt[id] = tot;
}
p = trie[p].nxt[id];
trie[p].cnt += v;
}
}
int minXor(int x)
{
int res = 0, p = 1;
for (int i = 31; i >= 0; i--)
{
int id = x >> i & 1;
if (trie[p].nxt[id] and trie[trie[p].nxt[id]].cnt)
p = trie[p].nxt[id];
else
{
p = trie[p].nxt[id ^ 1];
res |= 1 << i;
}
}
return res;
}
// Trie Implementation ends
int main()
{
cin >> n >> q;
for (int i = 1; i <= n; i += 1)
{
cin >> a[i];
}
for (int i = 1; i <= q; i += 1)
{
cin >> l >> r >> x;
queries.push_back({{l, r}, {x, i}});
}
sort(queries.begin(), queries.end());
int left = 1, right = 1;
for (int i = 0; i < q; i += 1)
{
int l = queries[i].first.first;
int r = queries[i].first.second;
int x = queries[i].second.first;
int index = queries[i].second.second;
while (left < l)
{
update(a[left], -1);
left += 1;
}
while (right <= r)
{
update(a[right], 1);
right += 1;
}
ans[index] = minXor(x);
}
for (int i = 1; i <= q; i += 1)
{
cout << ans[i] << " \n";
}
return 0;
}
Edit: with O(number of bits) code
Use a binary tree to store the values of A, look here : Minimum XOR for queries
What you need to change is adding to each node the range of indexes for A corresponding to the values in the leafs.
# minimal xor in a range
nbits=16 # Number of bits for numbers
asize=5000 # Array size
ntest=50 # Number of random test
from random import randrange
# Insert element a iindex iin the tree (increasing i only)
def tinsert(a,i,T):
for b in range(nbits-1,-1,-1):
v=((a>>b)&1)
T[v+2].append(i)
if T[v]==[]:T[v]=[[],[],[],[]]
T=T[v]
# Buildtree : builds a tree based on array V
def build(V):
T=[[],[],[],[]] # Init tree
for i,a in enumerate(V): tinsert(a,i,T)
return(T)
# Binary search : is T intersec [a,b] non empty ?
def binfind(T,a,b):
s,e,om=0,len(T)-1,-1
while True:
m=(s+e)>>1
v=T[m]
if v<a:
s=m
if m==om: return(a<=T[e]<=b)
elif v>b:
e=m
if m==om: return(a<=T[s]<=b)
else: return(True) # a<=T(m)<=b
om=m
# Look for the min xor in a give range index
def minx(x,s,e,T):
if s<0 or s>=(len(T[2])+len(T[3])) or e<s: return
r=0
for b in range(nbits-1,-1,-1):
v=((x>>b)&1)
if T[v+2]==[] or not binfind(T[v+2],s,e): # not nr with b set to v ?
v=1-v
T=T[v]
r=(r<<1)|v
return(r)
# Tests the code on random arrays
max=(1<<nbits)-1
for i in range(ntest):
A=[randrange(0,max) for i in range(asize)]
T=build(A)
x,s=randrange(0,max),randrange(0,asize-1)
e=randrange(s,asize)
if min(v^x for v in A[s:e+1])!=x^minx(x,s,e,T):
print('error')
I was able to solve this using segment tree and tries as suggested by #David Eisenstat
Below is an implementation in c++.
I constructed a trie for each segment in the segment tree. And finding the minimum xor is just traversing and matching the corresponding trie using each bit of the query value (here)
#include <bits/stdc++.h>
#define rep(i, a, b) for (int i = a; i < b; i++)
using namespace std;
const int bits = 7;
struct trie {
trie *children[2];
bool end;
};
trie *getNode(void)
{
trie *node = new trie();
node->end = false;
node->children[0] = NULL;
node->children[1] = NULL;
return node;
}
trie *merge(trie *l, trie *r)
{
trie *node = getNode();
// Binary 0:
if (l->children[0] && r->children[0])
node->children[0] = merge(l->children[0], r->children[0]);
else if (!r->children[0])
node->children[0] = l->children[0];
else if (!l->children[0])
node->children[0] = r->children[0];
// Binary 1:
if (l->children[1] && r->children[1])
node->children[1] = merge(l->children[1], r->children[1]);
else if (!r->children[1])
node->children[1] = l->children[1];
else if (!l->children[1])
node->children[1] = r->children[1];
return node;
}
void insert(trie *root, int num)
{
int mask = 1 << bits;
int bin;
rep(i, 0, bits + 1)
{
bin = ((num & mask) >> (bits - i));
if (!root->children[bin]) root->children[bin] = getNode();
root = root->children[bin];
mask = mask >> 1;
}
root->end = true;
}
struct _segTree {
int n, height, size;
vector<trie *> tree;
_segTree(int _n)
{
n = _n;
height = (int)ceil(log2(n));
size = (int)(2 * pow(2, height) - 1);
tree.resize(size);
}
trie *construct(vector<int> A, int start, int end, int idx)
{
if (start == end) {
tree[idx] = getNode();
insert(tree[idx], A[start]);
return tree[idx];
}
int mid = start + (end - start) / 2;
tree[idx] = merge(construct(A, start, mid, 2 * idx + 1),
construct(A, mid + 1, end, 2 * idx + 2));
return tree[idx];
}
int findMin(int num, trie *root)
{
int mask = 1 << bits;
int bin;
int rnum = 0;
int res = 0;
rep(i, 0, bits + 1)
{
bin = ((num & mask) >> (bits - i));
if (!root->children[bin]) {
bin = 1 - bin;
if (!root->children[bin]) return res ^ num;
}
rnum |= (bin << (bits - i));
root = root->children[bin];
if (root->end) res = rnum;
mask = mask >> 1;
}
return res ^ num;
}
int Query(int X, int start, int end, int qstart, int qend, int idx)
{
if (qstart <= start && qend >= end) return findMin(X, tree[idx]);
if (qstart > end || qend < start) return INT_MAX;
int mid = start + (end - start) / 2;
return min(Query(X, start, mid, qstart, qend, 2 * idx + 1),
Query(X, mid + 1, end, qstart, qend, 2 * idx + 2));
}
};
int main()
{
int n, q;
vector<int> A;
vector<int> L;
vector<int> R;
vector<int> X;
cin >> n;
A.resize(n, 0);
rep(i, 0, n) cin >> A[i];
cin >> q;
L.resize(q);
R.resize(q);
X.resize(q);
rep(i, 0, q) cin >> L[i] >> R[i] >> X[i];
//---------------------code--------------------//
_segTree segTree(n);
segTree.construct(A, 0, n - 1, 0);
rep(i, 0, q)
{
cout << segTree.Query(X[i], 0, n - 1, L[i], R[i], 0) << " ";
}
return 0;
}
Time complexity : O((2n - 1)*k + qklogn)
Space complexity : O((2n - 1)*2k)
k -> number of bits

Print Sum of int > 0

Given a number S ( int > 0 ) and n (int > 0), print all the different subsets of len n which sum to S.
For S = 7 and n = 3, the output is the following, the output must be descending order:
5 + 1 + 1
4 + 2 + 1
3 + 3 + 1
3 + 2 + 2
Here is what I've tried so far:
vector<vector<int> > partitions(int X, int Y)
{
vector<vector<int> > v;
if (X <= 1 && X <= X - Y + 1)
{
v.resize(1);
v[0].push_back(X);
return v;
}
for (int y = min(X - 1, Y); y >= 1; y--)
{
vector<vector<int> > w = partitions(X - y, y);
for (int i = 0; i<w.size(); i++)
{
w[i].push_back(y);
v.push_back(w[i]);
}
}
return v;
}
int main()
{
vector<vector<int> > v = partitions(7, 3);
int i;
for (i = 0; i<v.size(); i++)
{
int x;
for (x = 0; x<v[i].size(); x++)
printf("%d ", v[i][x]);
printf("\n");
}
}
the first element in the matrix is s- n + 1 and full of 1 till the sum is reached, or if the s-n+1 is equal to s, then n is 1, so only s will be the solution.
p.s.: I don t know if this problem has a particular name
This may not be the best solution for your problem, since it's not a dynamic programming based solution. In this case, I'm using recursion to fill an array until I reduce the desired number to 0. In this solution, every combination will be stored in the increasing order of the elements so we prevent permutations of a already calculated solution.
#include <iostream>
void findCombinationGivenSize(int numbersArray[], int index, int num, int reducedNum, int maxNum){
if (reducedNum < 0)
return; // this is our base case
if (reducedNum == 0 && index == maxNum){ // both criteria were attended:
//the sum is up to num, and the subset contain maxNum numbers
for (int i = index - 1; i>=0; i--)
std::cout<< numbersArray[i] << " + ";
// here we will have a problem with an extra '+' on the end, but you can figure out easily how to remove it :)
std::cout<<std::endl;
return;
}
// Find the previous number stored in arrayNumber[]
int prev;
if(index == 0)
prev = 1;
else
prev = numbersArray[index-1];
for (int k = prev; k <= num; k++){
// next element of array is k
numbersArray[index] = k;
// call recursively with reduced number
findCombinationGivenSize(numbersArray, index + 1, num,reducedNum - k, maxNum);
}
}
void findCombinations(int number, int maxSubset){
int arrayNumbers[number];
findCombinationGivenSize(arrayNumbers, 0, number, number, maxSubset);
}
int main(){
int number = 7;
int maxPartitions = 3;
findCombinations(number, maxPartitions);
return 0;
}

Min Unique Characters

REF: Ques 5 on this link: http://www.geeksforgeeks.org/directi-programming-questions
Given: two strings X and Y , with only one operation possible i.e swap the corresponding letters of X and Y ( i.e. X[i] and Y[i] ) which can be performed any number of times.
n(X) : number of unique characters in X
n(Y) : number of unique characters in Y
Problem : By Using the swap operations , Find the minimum possible values of max(n(X),n(Y))
INPUT:
ababa
babab
OUTPUT:
1
--------------------
INPUT:
abaaa
baaac
OUTPUT:
2
Please help me correct my solution or solve this problem with a better approach.
My Approach (Works For first and many other testcases but not the second one ) :
for(int i=0; i<x;i++)
{
if((count1[st1[i]]!=-1)||(count2[st2[i]]!=-1))
{
if(st1[i]!=st2[i])
{
if(count1[st1[i]]!=-1)
count1[st1[i]]++;
if(count2[st2[i]]!=-1)
count2[st2[i]]++;
}
else
{
ans++;
count1[st1[i]]=-1;
count2[st1[i]]=-1;
}
}
}
for(int i=97;i<123;i++)
{
if(count1[i]>0)
c1++;
if(count2[i]>0)
c2++;
if((count1[i]>0)&&(count2[i]>0))
com++;
}
un = max(c1,c2);
ans+= un-com/2;
printf("%lld\n",ans);
I'm not sure that I understood your algorithm, but here is brute-force version, which works for strings up-to 64 symbols length:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#define max(a,b) (a >= b ? a : b)
#define min(a, b) (a <= b ? a : b)
#define swap(a, b, idx) (a[idx] = a[idx] ^ b[idx] ^ (b[idx] = a[idx]))
int unique(char*a) {
char c[256] = { 0 };
int u = 0;
while (*a) {
u += (c[*a] == 0);
c[*a++] = 1;
}
return u;
}
void swapWithMask(char* a, char* b, unsigned long int mask, int l) {
for (int j = 0; j < l; j++)
if ((mask & (1 << j)) != 0)
swap(a, b, j);
}
int minUnique(char*oa, char*ob) {
int l = strlen(oa);
int minu = l;
char *a = malloc(l + 1);
strcpy(a, oa);
char *b = malloc(l + 1);
strcpy(b, ob);
unsigned long int m = (1 << l);
for (unsigned long int i = 0; i < m; i++) {
swapWithMask(a, b, i, l);
minu = min(max(unique(a), unique(b)), minu);
swapWithMask(a, b, i, l);
}
free(b);
free(a);
return minu;
}
int main(void) {
puts((minUnique("directi", "itcerid") == 4) ? "ok" : "fail");
puts((minUnique("ababa", "babab") == 1) ? "ok" : "fail");
puts((minUnique("abaaa", "baabb") == 2) ? "ok" : "fail");
return 0;
}

Calculating Execution time and big O time of my c++ program

My Code is:
#include <iostream>
#include <utility>
#include <algorithm>
//#include <iomanip>
#include <cstdio>
//using namespace std;
inline int overlap(std::pair<int,int> classes[],int size)
{
std::sort(classes,classes+size);
int count=0,count1=0,count2=0;
int tempi,tempk=1;
for(unsigned int i=0;i<(size-1);++i)
{
tempi = classes[i].second;
for(register unsigned int j=i+1;j<size;++j)
{
if(!(classes[i].first<classes[j].second && classes[i].second>classes[j].first))
{ if(count1 ==1)
{
count2++;
}
if(classes[i].second == tempi)
{
tempk =j;
count1 = 1;
}
////cout<<"\n"<<"Non-Overlapping Class:\t";
////cout<<classes[i].first<<"\t"<<classes[i].second<<"\t"<<classes[j].first<<"\t"<<classes[j].second<<"\n";
classes[i].second = classes[j].second;
count++;
if(count1==1 && j ==(size-1))
{
j= tempk;
classes[i].second = tempi;
count1= 0;
if(count2 !=0)
{
count = (count + ((count2)-1));
}
count2 =0;
}
}
else
{
if(j ==(size-1))
{
if(count>0)
{
j= tempk;
classes[i].second = tempi;
count1= 0;
if(count2 !=0)
{
count = (count + ((count2)-1));
}
count2 =0;
}
}
}
}
}
count = count + size;
return count;
}
inline int fastRead_int(int &x) {
register int c = getchar_unlocked();
x = 0;
int neg = 0;
for(; ((c<48 || c>57) && c != '-'); c = getchar_unlocked());
if(c=='-') {
neg = 1;
c = getchar_unlocked();
}
for(; c>47 && c<58 ; c = getchar_unlocked()) {
x = (x<<1) + (x<<3) + c - 48;
}
if(neg)
x = -x;
return x;
}
int main()
{
int N;
////cout<<"Please Enter Number Of Classes:";
clock_t begin,end;
float time_interval;
begin = clock();
while(fastRead_int(N))
{
switch(N)
{
case -1 : end = clock();
time_interval = float(end - begin)/CLOCKS_PER_SEC;
printf("Execution Time = %f",time_interval);
return 0;
default :
unsigned int subsets;
unsigned int No = N;
std::pair<int,int> classes[N];
while(No--)
{
////cout<<"Please Enter Class"<<(i+1)<<"Start Time and End Time:";
int S, E;
fastRead_int(S);
fastRead_int(E);
classes[N-(No+1)] = std::make_pair(S,E);
}
subsets = overlap(classes,N);
////cout<<"\n"<<"Total Number Of Non-Overlapping Classes is:";
printf("%08d",subsets);
printf("\n");
break;
}
}
}
and Input and output of my program:
Input:
5
1 3
3 5
5 7
2 4
4 6
3
500000000 1000000000
1 5
1 5
1
999999999 1000000000
-1
Output:
Success time: 0 memory: 3148 signal:0
00000012
00000005
00000001
Execution Time = 0.000036
I tried to calculate by having clocks at start of main and end of main and found out the time.But it said only some 0.000036 secs.But when I tried to post the same code in Online Judge(SPOJ).My program got 'Time Limit Exceeded' Error. Time Limit for the above program in SPOJ is 2.365 secs.Could somebody help me figure out this?
I consider that your question is about the overlap function.
In it, you have
A sort call: O(n×ln(n))
two for loops:
the first is roughly 0..Size
the second (nested in the first) is roughly i..Size
The inside of the second loop is called Size(Size+1) / 2 (reverse sum of the N first integer) times with no breaks.
So your algorithm is O(n²) where n is the size.

Getting wrong answer for Project Euler #27

I'm working on Project Euler #27 in C++:
Euler published the remarkable quadratic formula:
n² + n + 41
It turns out that the formula will produce 40 primes for the
consecutive values n = 0 to 39. However, when n = 40, 40² + 40 + 41 =
40(40 + 1) + 41 is divisible by 41, and certainly when n = 41, 41² +
41 + 41 is clearly divisible by 41.
Using computers, the incredible formula n² − 79n + 1601 was
discovered, which produces 80 primes for the consecutive values n = 0
to 79. The product of the coefficients, −79 and 1601, is −126479.
Considering quadratics of the form:
n² + an + b, where |a| < 1000 and |b| < 1000
where |n| is the modulus/absolute value of n
e.g. |11| = 11 and |−4| = 4
Find the product of the coefficients, a and b, for the quadratic
expression that produces the maximum number of primes for consecutive
values of n, starting with n = 0.
I keep getting -60939 when the real answer is -59231. What am I missing?
#include <iostream>
#include "Helper.h"
using namespace std;
int formula(int a, int b, int n) {
return ((n * n) + (a * n) + b);
}
int main() {
int most = 0;
int ansA = 0;
int ansB = 0;
bool end = false;
for(int a = 999; a >= -999; a--) {
for(int b = 999; b >= 2; b--) { //b must be prime
if(Helper::isPrime(b)) {
end = false;
for(int n = 0; !end; n++) {
if(!Helper::isPrime(formula(a, b, n))) {
if(n-1 > most) {
most = n-1;
ansA = a;
ansB = b;
}
end = true;
}
}
}
}
}
cout << ansA << " * " << ansB << " = " << ansA * ansB << " with " << most << " primes." << endl;
return 0;
}
In case it's the problem, here is my isPrime function:
bool Helper::isPrime(int num) {
if(num == 2)
return true;
if(num % 2 == 0 || num == 1 || num == 0)
return false;
int root = (int) sqrt((double)num) + 1;
for(int i = root; i >= 2; i--) {
if (num % i == 0)
return false;
}
return true;
}
You are allowing a to be negative, and your formula returns an int. Does calling Helper::isPrime with a negative number even make sense (in other words, does Helper::isPrime take an unsigned int?)
Here is my java version. Hope it helps:
static int function(int n, int a, int b){
return n*n + a*n + b;
}
static int consequitive_Primes(int a, int b, HashSet<Integer> primes){
int n = 0;
int number = 0;
while(true){
if(!primes.contains(function(n, a, b)))
break;
number++;
n++;
}
return number;
}
static HashSet<Integer> primes (int n){
ArrayList<Integer> primes = new ArrayList<Integer>();
primes.add(3);
for(int i=3; i<n;i+=2){
boolean isPrime = true;
for(Integer k:primes){
if(i%k==0){
isPrime = false;
break;
}
}
if(isPrime) primes.add(i);
}
return new HashSet<Integer>(primes);
}
static long q27(){
HashSet<Integer> primes = primes(1000);
int max = 0;
int max_ab = 0;
for(int a = -999; a<1000;a++){
for(int b = -999; b<1000;b++){
int prime_No = consequitive_Primes(a,b,primes);
if(max<prime_No){
max = prime_No;
max_ab = a*b;
}
}
}
return max_ab;
}