I need to convert this recursive function into tail recursive function but i am getting the wrong output can any help me out with this.
Here is the function definition:
f(n) = 3f(n − 1) - f(n − 2) + n,
with initial conditions f(0) = 1 and f(1) = 2.
#include <iostream>
using namespace std;
int headRecursion(int n) {
if(n == 0) {
return 1;
}
if (n == 1) {
return 2;
}
return 3 * headRecursion(n - 1) - headRecursion(n - 2) + n;
}
int main(){
cout << endl << headRecursion(3);
return 0;
}
This is kind of an interesting problem. We can start with how to implement as a loop:
int minus2 = 1;
int minus1 = 2;
if (n == 0) return minus2;
if (n == 1) return minus1;
for( int i = 2; i <= n; i++)
{
int next = minus1 * 3 - minus2 + i;
minus2 = minus1;
minus1 = next;
}
return minus1;
The takeaway is we need to count UP. In order to make this tail recursive we need to pass in our accumulators (there is no reason to do this other than to show off, but it adds nothing to readability or efficiency)
int tailRecursive(int minus2, int minus1, int step, int n)
{
if (step == n) return minus1;
return tailRecursive(minus1, minus1*3 - minus2 + step+1, step+1, n);
}
you can use an intermediate to set it up and handle the n==0 case.
int calcIt(int n) {
if (n == 0) return 1;
// step must start with 1, since we handled 0 above
return tailRecursive(1, 2, 1, n);
}
Something along these lines:
std::pair<int, int> next_result(std::pair<int, int> prev_result, int n) {
return {3*prev_result.first - prev_result.second + n, prev_result.first};
}
std::pair<int, int> tailRecursion(int n) {
if (n == 0) {
return {1, 0};
}
if (n == 1) {
return {2, 1};
}
return next_result(tailRecursion(n-1), n);
}
int compute(int n) {
return tailRecursion(n).first;
}
int main(){
std::cout << compute(3) << std::endl;
}
Demo
The key is that you need a function that computes a pair {f(n), f(n-1)} given the previously computed pair {f(n-1), f(n-2)}
Related
Among the given input of two numbers, check if the second number is exactly the next prime number of the first number. If so return "YES" else "NO".
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int nextPrime(int x){
int y =x;
for(int i=2; i <=sqrt(y); i++){
if(y%i == 0){
y = y+2;
nextPrime(y);
return (y);
}
}
return y;
}
int main()
{
int n,m, x(0);
cin >> n >> m;
x = n+2;
if(n = 2 && m == 3){
cout << "YES\n";
exit(0);
}
nextPrime(x) == m ? cout << "YES\n" : cout << "NO\n";
return 0;
}
Where is my code running wrong? It only returns true if next number is either +2 or +4.
Maybe it has something to do with return statement.
I can tell you two things you are doing wrong:
Enter 2 4 and you will check 4, 6, 8, 10, 12, 14, 16, 18, ... for primality forever.
The other thing is
y = y+2;
nextPrime(y);
return (y);
should just be
return nextPrime(y + 2);
Beyond that your loop is highly inefficient:
for(int i=2; i <=sqrt(y); i++){
Handle even numbers as special case and then use
for(int i=3; i * i <= y; i += 2){
Using a different primality test would also be faster. For example Miller-Rabin primality test:
#include <iostream>
#include <cstdint>
#include <array>
#include <ranges>
#include <cassert>
#include <bitset>
#include <bit>
// square and multiply algorithm for a^d mod n
uint32_t pow_n(uint32_t a, uint32_t d, uint32_t n) {
if (d == 0) __builtin_unreachable();
unsigned shift = std::countl_zero(d) + 1;
uint32_t t = a;
int32_t m = d << shift;
for (unsigned i = 32 - shift; i > 0; --i) {
t = ((uint64_t)t * t) % n;
if (m < 0) t = ((uint64_t)t * a) % n;
m <<= 1;
}
return t;
}
bool test(uint32_t n, unsigned s, uint32_t d, uint32_t a) {
uint32_t x = pow_n(a, d, n);
//std::cout << " x = " << x << std::endl;
if (x == 1 || x == n - 1) return true;
for (unsigned i = 1; i < s; ++i) {
x = ((uint64_t)x * x) % n;
if (x == n - 1) return true;
}
return false;
}
bool is_prime(uint32_t n) {
static const std::array witnesses{2u, 3u, 5u, 7u, 11u};
static const std::array bounds{
2'047u, 1'373'653u, 25'326'001u, 3'215'031'751u, UINT_MAX
};
static_assert(witnesses.size() == bounds.size());
if (n == 2) return true; // 2 is prime
if (n % 2 == 0) return false; // other even numbers are not
if (n <= witnesses.back()) { // I know the first few primes
return (std::ranges::find(witnesses, n) != std::end(witnesses));
}
// write n = 2^s * d + 1 with d odd
unsigned s = 0;
uint32_t d = n - 1;
while (d % 2 == 0) {
++s;
d /= 2;
}
// test widtnesses until the bounds say it's a sure thing
auto it = bounds.cbegin();
for (auto a : witnesses) {
//std::cout << a << " ";
if (!test(n, s, d, a)) return false;
if (n < *it++) return true;
}
return true;
}
And yes, that is an awful lot of code but it runs very few times.
Something to do with the return statement
I would say so
y = y+2;
nextPrime(y);
return (y);
can be replaced with
return nextPrime(y + 2);
Your version calls nextPrime but fails to do anything with the return value, instead it just returns y.
It would be more usual to code the nextPrime function with another loop, instead of writing a recursive function.
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
For 2 numbers x and n entered by the user, my code needs to find Hn(x) defined recursively by the following formulas:
I am trying to implement a recursive version and and iterative version of that function. But I think I am getting the wrong concept of it, since my code doesn't compile due to errors on H(n) and H[n]:
#include "pch.h"
#include <iostream>
int H(int n, int x) //function for recursion
{
if (n < 0) return -1;
else if (n == 0) return 1;
else if (n == 1) return 2 * x;
return 2 * x * H(n) * x - 2 * n * H(n - 1) * x;
}
int H1(int n, int x) //function for Iterator
{
int *H1 = new int[n + 1];
H[0] * x = 1;
H[1] * x = 2 * x;
for (int i = 0; i <= n; i++)
{
H[i] * x = 2 * x * H[n] * x - 2 * n * H[n - 1] * x;
}
return H1(n) * x;
}
int main()
{
int n, x;
std::cout << "Enter the number n: ";
std::cin >> n;
std::cout << "Enter the number x: ";
std::cin >> x;
std::cout << "Rec = " << H[n] * x std::endl;
std::cout << "Iter = " << H1[n] * x std::endl;
}
It is confusing, I apologize for that as I am completely new to functions.
I already managed to do this with fibonacci sequence. And there I used only one parameter for function f(x) that is f(int n){... }, but here I am a bit confused with two parameters in function H(int n, int x) , where n is the index of H while x is an integer.
Yes, you need to translate your matematically indexed function into a function with 2 parameters.
The recursive version is almost ok, except for some shifts in the indexes:
int H(int n, int x) // recursive version
{
if (n <= 0)
return -1;
else if (n == 1)
return 1;
else if (n == 2)
return 2 * x;
else
return 2 * x * H(n-1, x) - 2 * n * H(n - 2, x); // shift n+1, n n-1 to n, n-1 n-2
}
Your iterative version needs rework, since you should write it as a loop, if possible without cashing the values that you no longer need. For example:
int Hi(int n, int x) //iterative version
{
if (n <= 0)
return -1;
else if (n == 1)
return 1;
int am2 = 1; // start for for n-2
int am1 = 2*x; // start for n-1
if (n == 2)
return am1;
int am;
for (int i=3; i<=n; i++) {
am = 2*x*am1 - 2*i*am2; // calculate Hn from Hn-1 and Hn-2
//prepare next interation
am2=am1;
am1=am;
}
return am;
}
Online demo
You wrote:
int H(int n, int x) //function for recursion
{
if (n < 0) return -1;
else if (n == 0) return 1;
else if (n == 1) return 2 * x;
return 2 * x * H(n) * x - 2 * n * H(n - 1) * x;
}
You're not far from a working program. Drop that H1 function. Let's see:
int H(int n, int x)
{
switch(n)
{
// H_0(x) = 1
case 0: return 1;
// H_1(x) = 2x
case 1: return 2 * x;
// H_{n+1}(x) = 2x H_n(x) - 2n H_{n - 1}(x)
default:
return 2*x*H(n-1, x) - 2*(n-1)*H(n-2, x);
}
}
The trick part is realizing than the n in H_{n+1}(x) = 2x H_n(x) - 2n H_{n - 1}(x) and in return 2*x*H(n-1, x) - 2*(n-1)*H(n-2, x);are not the same, they differ by one.
Now, you only need to handle user I/O and calling your H function with user input.
I have made a function and I am trying to make it recursive. Does anyone have any tips on how I can make this function recursive? I know recursive means to use the function in the function itself.
int countEven(int n){
int evens = 0;
if(n <= 0) return 0; //base case
while(n > 0){
int digit = n%10; //get the last digit
if(digit%2 == 0){
evens = evens + 1;
}
n = n/10;
}
cout << evens;
}
int rec(int n)
{
int sum = 0;
if(n<=0)
return 0;
else if ((n%10)%2==0)
sum = rec(n/10)+1;
else
sum = rec(n/10);
return sum;
}
Maybe something like this :)
For counting the even digits of an integer base 10 you can simplify the function to the following
int countEven(int n)
{
if (n != 0) return !(n % 2) + countEven(n/10);
else return 0;
}
This expands as follows. Assume n = 258:
countEven(258) =
1 + countEven(25) =
1 + 0 + countEven(2) =
1 + 0 + 1 + countEven(0) = 2
Note that the statement !(n % 2) returns 1 if n is even and 0 if it's odd.
For shorter you can do the following:
int ce(int n) { return n ? !(n&1) + ce(n/10) : 0; }
using the ternary operator.
seems like you're trying to count the even digits in a number
int countEven(int n){
if(n == 0)
return 0; //base case
if (n<10)
return !(n%2);
return !(n%2)+countEven(n/10);
}
looks like a similar question i received from QC.
to make it recursive, you must have the function calling onto itself. Ask how you can make the the input simpler and have some sort of base so that the function doesn't break.
int countEven(int number) {
if (x <= 0) return 0;
if (x % 2 == 0) {
return countEven(number / 10) + 1;
}
return countEven(number / 10)
}
I have an integer positive number n. Let's say n=5 for example. If we look at multiplies of n, we see these numbers (let's call it n-grid) [... -15, -10, -5, 0, 5, 10, 15, ...]. Now I need to write a function F(n, N) that, given an integer N, outputs a closest number from that n-grid. For instance, F(n, 0) = 0 (for any n). F(5, 4) = 5, F(5, 7) = 5, F(5, 8) = 10, F(5, -13) = -15 and so on.
I've written this function:
int const x = ((::abs(N) + (n / 2)) / n) * n;
if (N > 0)
{
return x;
}
else
{
return -x;
}
It seems to work but don't like how it looks. Can anybody suggest any improvement?
You could possibly get rid of the if statement by multiplying x by (N/abs(N)) and returning the calculated value immeadiatelly, without even saving it in x.
I would not do this however, because it would harm readability.
This might be simple to understand and to look even,
int grid(int n, int N){
if (N == 0) return N;
return n * (N > 0 ? (n + N)/n : (n + abs(N))/n );
}
Here is the ideone result.
int closest_number(int n,int N)
{
if(N==0)
return N;
else if(N > 0)
{
int temp = N % n;
if(temp > (n/2))
return (n*((N/n)+1));
else
return (n*(N/n));
}
else
{
int temp = N % n;
if(abs(temp) > (n/2))
return (n*((N/n)-1));
else
return (n*(N/n));
}
}
You can find the ideone output for the given set of test cases here http://ideone.com/NlJiPt
here is simple math solution :-
F(k,x) = (x/k)*k if abs(x-(x/k)*k) <= k/2
= (x/k)*k + sign(x)*k otherwise
C Implementation :-
#include<stdio.h>
#include<math.h>
int func(int k,int x) {
int a = (x/k)*k;
int sign = x/abs(x);
if(abs(x-a)<=k/2)
return(a);
else return(a+sign*k);
}
int main() {
printf("%d",func(5,121));
return 0;
}
You are describing a rounding algorithm; you need to specify whether rounding is symmetric or not, and then whether it is up or down (or toward/away from zero for symmetric). ideone demo for below code.
// F(4, 6) F(4, -6)
int symmetricTowardZero(int n, int N) {
return n * (int)(N / n); // 4 -4
}
int symmetricAwayFromZero(int n, int N) {
return n * (int)(N / n + (N < 0 ? -0.5 : +0.5)); // 8 -8
}
int unsymmetricDownward(int n, int N) {
return n * floor((double)N / n); // 4 -8
}
int unsymmetricUpward(int n, int N) {
return n * ceil((double)N / n); // 8 -4
}