Iteration n * F(n - 1)+((n - 1) * F(n - 2)) - algorithm

I am stuck with this: n * F(n - 1)+((n - 1) * F(n - 2)), I know how to write this recursively. But no idea about the iteration.
I use this for recursion:
long F_r(int n)
{
if (n <= 2)
{
return 1;
}
else if (n > 2)
{
return n * F_r(n - 1) + ((n - 1) * F_r(n - 2));
}
}
Can someone help me, please?

To understand the iteration just simulate for n = 3 or some other values (greater than 3 will help better). Let's start with n = 0, 1, 2, 3, 4, ... and see how the values of F gets calculated:
F(0) = 1;
F(1) = 1;
F(2) = 1;
F(3) = 3* F(2) + (2* F(1));
= 3*1 + (2*1);
= 3 + 2;
= 5;
F(4) = 4* F(3) + (3* F(2));
= 4*5 + (3*1);
= 20 + 3;
= 23;
And so on.

With an array for storing all intermediate values of F:
long F_r(int n)
{
long[] f = new long [n + 1]; // f[0] is not used
f[1] = 1;
f[2] = 1;
for (int i = 3; i <= n; i++)
{
f[i] = i * f[i - 1] + ((i - 1) * f[i - 2]); // the formula goes here
}
return f[n];
}
If you want to use only O(1) space, note that you don't need to store the whole array, only the previous two values at each point of time.
So, this can be rewritten as in fgb's answer.

To write it as an iterative algorithm, you can write something in the form of:
long F(int n) {
long a = 1;
long b = 1;
long c = 1;
for(int x = 3; x <= n; x++) {
a = b;
b = c;
c = ...
}
return c;
}

Just for fun -- solving the recurrence relation with Wolfram Alpha, we get:
F(n) = (2 * factorial(n + 2) - 5 * subfactorial(n + 2)) / (n + 1)
Which we can calculate as:
long F(int n) {
long p = 1;
long q = 1;
for (int i = 1; i <= n + 2; i++) {
p *= i;
q = q * i + (1 - (i % 2) * 2);
}
return (2 * p - 5 * q) / (n + 1);
}

Related

C++ algorithm code for Magical sequence that will generate desired output

The Magical Sequence
A Magical Sequence is defined as shown.
Magical[1] = 0
Magical[2] = 1
Magical[n] = Magical[n-1] + 2*Magical[n-2] + 3*Magical[n-3] + ... (n-1)*Magical[1] + n*1., for n > 2
Given n (1 <= n <= 10^9 ), find Magical[n].
Example 1: input: 3
Output: 4
Explanation:
Magical[n] = 1*Magical[n-1] + 2*Magical[n-2] + 3*1
Magical[3] = 1*Magical[2] + 2*Magical[1] + 3*1
Magical[3] = 1*1 + 2*0 + 3*1
Magical[3] = 4
Example 2: input: 4
Output: 10
Magical[4] = 1*Magical[3]+2*Magical[2]+3*Magical[1]+4*1
= 1*4+2*1+3*0+4 = 10
Example 3: input: 5
Output: 26
Magical[5] = 1*Magical[4]+2*Magical[3]+3*Magical[2]+4*Magical[1]+5*1
= 1*10+2*4+3*1+4*0+5 = 26
I tried something like below :-
int CuckooNum(int n)
{
if (1 == n)
{
return 0;
}
else if (2 == n)
{
return 1;
}
std::vector<int> vec;
vec.resize(n);
vec[0] = 4;
vec[1] = 0;
vec[2] = 1;
int multiplyer = n;
int result = 0;
for (int index=3; index <= n; index++)
{
result += multiplyer * vec[index-1];
vec[index] = result;
multiplyer--;
}
return result;
}
long long func(int n)
{
if (n==1) return 0;
else if (n==2) return 1;
else return 1*func(n-1)+2*func(n-2)+n;
}
As the size n can be very large (10^9), a direct implementation O(n^2) is not possible.
A specific algorithm is needed. I will focus here on the algorithm, and propose a O(log n) solution.
To simplify explanation, I rename magical[] as x[]
Moreover, we can define x[0] = 1. Then,
x[n] = x[n-1] + 2*x[n-2] + 3*x[n-3] + ... (n-1)*x[1] + n*x[0]
As
x[n-1] = 1*x[n-2] + 2*x[n-3] + ... (n-2)*x[1] + (n-1)*x[0]
It follows
x[n] - x[n-1] = x[n-1] + x[n-2] + x[n-3] + ... x[1] + x[0] = S[n-1]
When S[n] represents the sum of the terms until n (x[0] included)
Moreover,
S[n] = S[n-1] + x[n] = 2*S[n-1] + x[n-1]
Therefore, the iterative formula can be represented in a simple matrix form:
(x[n]) = (1 1) (x[n-1])
(S[n]) (1 2) (S[n-1])
Or, defining the vector (x[n] S[n])^t as Z[n]:
Z[n] = A * Z[n-1] where A is the matrix (1 1)
(1 2)
Note: this formula is valid for n>= 4 only, as the first x[n] values do no respect the simple recurrence relation.
It follows that
Z[n] = A^(n-3) Z[3] with Z[3] = (4 6)^t
Classically, this calculation can be performed with O(log n) complexity, iteratively calculating A^2, A^4, A^8 etc.
Pay attention that the values increase rapidly.
Here is an example of C++ implementation. Note that this implementation is not optimized, as for example it doesn't use the fact that all matrices are symmetric.
#include <iostream>
#include <array>
using Matr22 = std::array<std::array<long long int, 2>, 2>;
using Vect2 = std::array<long long int, 2>;
Matr22 Matrsquare (const Matr22 &m) {
Matr22 m2;
m2[0][0] = m[0][0]*m[0][0] + m[0][1]*m[1][0];
m2[0][1] = m[0][0]*m[0][1] + m[0][1]*m[1][1];
m2[1][0] = m[1][0]*m[0][0] + m[1][1]*m[1][0];
m2[1][1] = m[1][0]*m[0][1] + m[1][1]*m[1][1];
return m2;
}
Matr22 Mult (const Matr22 &m1, const Matr22 &m2) {
Matr22 y;
y[0][0] = m1[0][0]*m2[0][0] + m1[0][1]*m2[1][0];
y[0][1] = m1[0][0]*m2[0][1] + m1[0][1]*m2[1][1];
y[1][0] = m1[1][0]*m2[0][0] + m1[1][1]*m2[1][0];
y[1][1] = m1[1][0]*m2[0][1] + m1[1][1]*m2[1][1];
return y;
}
Vect2 Mult (const Matr22 &m, const Vect2& x) {
Vect2 y;
y[0] = m[0][0] * x[0] + m[0][1] * x[1];
y[1] = m[1][0] * x[0] + m[1][1] * x[1];
return y;
}
// Matrix exponentiation
Matr22 Mult_exp (const Matr22 &m, int exp) {
Matr22 y = {1, 0, 0, 1};
if (exp == 0) return y;
Matr22 M2k = m;
while (exp) {
if (exp%2) y = Mult (y, M2k);
M2k = Matrsquare (M2k);
exp /= 2;
};
return y;
}
long long int Magical (int n) {
if (n == 1) return 0;
if (n == 2) return 1;
if (n == 3) return 4;
Matr22 A = {1, 1, 1, 2};
Vect2 z = {4, 6}; // corresponds to n=3
auto Ak = Mult_exp (A, n-3);
z = Mult (Ak, z);
return z[0];
}
int main() {
int n;
std::cout << "Input n: ";
std::cin >> n;
auto ans = Magical (n);
std::cout << "Magical[" << n << "] = " << ans << '\n';
}

Derivation of runtime for triple nested for loop

I had to do a problem which required me to figure out the runtime for this snippet of code:
for (i = 1; i <= log(n); i = i + 1) {
for (j = 1; j <= 2*i; j = 2*j) {
for (k = 1; k <= log(j); k = k + 1) {
print("[some arbitrary string]");
}
}
}
It is obvious by inspection that this is Θ((log(n)^3), since each of the for loops is Θ(log(n)), but I'm not exactly sure what the best way to rigorously prove this is (using sums, for example).
Let's substitute log(n) with x (x = log(n)). Then
for (i = 1; i <= x; i = i + 1) {
for (j = 1; j <= 2*i; j = 2*j) {
for (k = 1; k <= log(j); k = k + 1) {
print("[some arbitrary string]");
}
}
}
In the second loop j runs through powers of 2. Let's take another loop with same asymptotics using another substitution: y = log(j):
for (i = 1; i <= x; i = i + 1) {
for (y = 0; y <= log(i); ++y) {
for (k = 1; k <= y; k = k + 1) {
print("[some arbitrary string]");
}
}
}
The complexity is O(x * log(x)^2) = O(log(n) * log(log(n))^2).

Express a given number as a sum of four squares

I am looking for an algorithm that expresses a given number as a sum of (up to) four squares.
Examples
       120 = 82 + 62 + 42 + 22
       6 = 02 + 12 + 12 + 22
       20 = 42 + 22 + 02+ 02
My approach
Take the square root and repeat this repeatedly for the remainder:
while (count != 4) {
root = (int) Math.sqrt(N)
N -= root * root
count++
}
But this fails when N is 23, even though there is a solution:
       32 + 32+ 22 + 12
Question
Is there any other algorithm to do that?
Is it always possible?
###Always possible?
Yes, the Lagrange's four square theorem states that:
every natural number can be represented as the sum of four integer squares.
It has been proved in several ways.
###Algorithm
There are some smarter algorithms, but I would suggest the following algorithm:
Factorise the number into prime factors. They don't have to be prime, but the smaller they are, the better: so primes are best. Then solve the task for each of these factors as below, and combine any resulting 4 squares with the previously found 4 squares with the Euler's four-square identity.
         (a2 + b2 + c2 + d2)
(A2 + B2 + C2 + D2) =
               (aA + bB + cC + dD)2 +
               (aB − bA + cD − dC)2 +
               (aC − bD − cA + dB)2 +
               (aD + bC − cB − dA)2
Given a number n (one of the factors mentioned above), get the greatest square that is not greater than n, and see if n minus this square can be written as the sum of three squares using the Legendre's three-square theorem: it is possible, if and only when this number is NOT of the following form:
        4a(8b+7)
If this square is not found suitable, try the next smaller one, ... until you find one. It guaranteed there will be one, and most are found within a few retries.
Try to find an actual second square term in the same way as in step 1, but now test its viability using Fermat's theorem on sums of two squares which in extension means that:
if all the prime factors of n congruent to 3 modulo 4 occur to an even exponent, then n is expressible as a sum of two squares. The converse also holds.
If this square is not found suitable, try the next smaller one, ... until you find one. It's guaranteed there will be one.
Now we have a remainder after subtracting two squares. Try subtracting a third square until that yields another square, which means we have a solution. This step can be improved by first factoring out the largest square divisor. Then when the two square terms are identified, each can then be multiplied again by the square root of that square divisor.
This is roughly the idea. For finding prime factors there are several solutions. Below I will just use the Sieve of Eratosthenes.
This is JavaScript code, so you can run it immediately -- it will produce a random number as input and display it as the sum of four squares:
function divisor(n, factor) {
var divisor = 1;
while (n % factor == 0) {
n = n / factor;
divisor = divisor * factor;
}
return divisor;
}
function getPrimesUntil(n) {
// Prime sieve algorithm
var range = Math.floor(Math.sqrt(n)) + 1;
var isPrime = Array(n).fill(1);
var primes = [2];
for (var m = 3; m < range; m += 2) {
if (isPrime[m]) {
primes.push(m);
for (var k = m * m; k <= n; k += m) {
isPrime[k] = 0;
}
}
}
for (var m = range + 1 - (range % 2); m <= n; m += 2) {
if (isPrime[m]) primes.push(m);
}
return {
primes: primes,
factorize: function (n) {
var p, count, primeFactors;
// Trial division algorithm
if (n < 2) return [];
primeFactors = [];
for (p of this.primes) {
count = 0;
while (n % p == 0) {
count++;
n /= p;
}
if (count) primeFactors.push({value: p, count: count});
}
if (n > 1) {
primeFactors.push({value: n, count: 1});
}
return primeFactors;
}
}
}
function squareTerms4(n) {
var n1, n2, n3, n4, sq, sq1, sq2, sq3, sq4, primes, factors, f, f3, factors3, ok,
res1, res2, res3, res4;
primes = getPrimesUntil(n);
factors = primes.factorize(n);
res1 = n > 0 ? 1 : 0;
res2 = res3 = res4 = 0;
for (f of factors) { // For each of the factors:
n1 = f.value;
// 1. Find a suitable first square
for (sq1 = Math.floor(Math.sqrt(n1)); sq1>0; sq1--) {
n2 = n1 - sq1*sq1;
// A number can be written as a sum of three squares
// <==> it is NOT of the form 4^a(8b+7)
if ( (n2 / divisor(n2, 4)) % 8 !== 7 ) break; // found a possibility
}
// 2. Find a suitable second square
for (sq2 = Math.floor(Math.sqrt(n2)); sq2>0; sq2--) {
n3 = n2 - sq2*sq2;
// A number can be written as a sum of two squares
// <==> all its prime factors of the form 4a+3 have an even exponent
factors3 = primes.factorize(n3);
ok = true;
for (f3 of factors3) {
ok = (f3.value % 4 != 3) || (f3.count % 2 == 0);
if (!ok) break;
}
if (ok) break;
}
// To save time: extract the largest square divisor from the previous factorisation:
sq = 1;
for (f3 of factors3) {
sq *= Math.pow(f3.value, (f3.count - f3.count % 2) / 2);
f3.count = f3.count % 2;
}
n3 /= sq*sq;
// 3. Find a suitable third square
sq4 = 0;
// b. Find square for the remaining value:
for (sq3 = Math.floor(Math.sqrt(n3)); sq3>0; sq3--) {
n4 = n3 - sq3*sq3;
// See if this yields a sum of two squares:
sq4 = Math.floor(Math.sqrt(n4));
if (n4 == sq4*sq4) break; // YES!
}
// Incorporate the square divisor back into the step-3 result:
sq3 *= sq;
sq4 *= sq;
// 4. Merge this quadruple of squares with any previous
// quadruple we had, using the Euler square identity:
while (f.count--) {
[res1, res2, res3, res4] = [
Math.abs(res1*sq1 + res2*sq2 + res3*sq3 + res4*sq4),
Math.abs(res1*sq2 - res2*sq1 + res3*sq4 - res4*sq3),
Math.abs(res1*sq3 - res2*sq4 - res3*sq1 + res4*sq2),
Math.abs(res1*sq4 + res2*sq3 - res3*sq2 - res4*sq1)
];
}
}
// Return the 4 squares in descending order (for convenience):
return [res1, res2, res3, res4].sort( (a,b) => b-a );
}
// Produce the result for some random input number
var n = Math.floor(Math.random() * 1000000);
var solution = squareTerms4(n);
// Perform the sum of squares to see it is correct:
var check = solution.reduce( (a,b) => a+b*b, 0 );
if (check !== n) throw "FAILURE: difference " + n + " - " + check;
// Print the result
console.log(n + ' = ' + solution.map( x => x+'²' ).join(' + '));
The article by by Michael Barr on the subject probably represents a more time-efficient method, but the text is more intended as a proof than an algorithm. However, if you need more time-efficiency you could consider that, together with a more efficient factorisation algorithm.
It's always possible -- it's a theorem in number theory called "Lagrange's four square theorem."
To solve it efficiently: the paper Randomized algorithms in number theory (Rabin, Shallit) gives a method that runs in expected O((log n)^2) time.
There is interesting discussion about the implementation here: https://math.stackexchange.com/questions/483101/rabin-and-shallit-algorithm
Found via Wikipedia:Langrange's four square theorem.
Here is solution , Simple 4 loops
max = square_root(N)
for(int i=0;i<=max;i++)
for(int j=0;j<=max;j++)
for(int k=0;k<=max;k++)
for(int l=0;l<=max;l++)
if(i*i+j*j+k*k+l*l==N){
found
break;
}
So you can test for any numbers. You can use break condition after two loops if sum exceeds then break it.
const fourSquares = (n) => {
const result = [];
for (let i = 0; i <= n; i++) {
for (let j = 0; j <= n; j++) {
for (let k = 0; k <= n; k++) {
for (let l = 0; l <= n; l++) {
if (i * i + j * j + k * k + l * l === n) {
result.push(i, j, k, l);
return result;
}
}
}
}
}
return result;
}
It's running too long
const fourSquares = (n) => {
const result = [];
for (let i = 0; i <= n; i++) {
for (let j = 0; j <= (n - i * i); j++) {
for (let k = 0; k <= (n - i * i - j * j); k++) {
for (let l = 0; l <= (n - i * i - j * j - k * k); l++) {
if (i * i + j * j + k * k + l * l === n) {
result.push(i, j, k, l);
return result;
}
}
}
}
}
return result;
}
const fourSquares = (n) => {
const result = [];
for (let i = 0; i * i <= n; i++) {
for (let j = 0; j * j <= n; j++) {
for (let k = 0; k * k <= n; k++) {
for (let l = 0; l * l <= n; l++) {
if (i * i + j * j + k * k + l * l === n) {
result.push(i, j, k, l);
return result;
}
}
}
}
}
return result;
}
const fourSquares = (n) => {
let a = Math.sqrt(n);
let b = Math.sqrt(n - a * a);
let c = Math.sqrt(n - a * a - b * b);
let d = Math.sqrt(n - a * a - b * b - c * c);
if (n === a * a + b * b + c * c + d * d) {
return [a, b, c, d];
}
}

Rabin Karp algorithm for big strings

I wrote a simple step-by-step implementation of Rabin-Karp algorithm for substring search, and it seems to work fine until the hash becomes greater than the modulus, and then it goes wrong...
Here is the code, it's quite simple:
typedef long long ll;
#define B 257
//base
#define M 2147483647
//modulus
//modulus for positive and negative values
ll mod(ll a){
return (a % M + M) % M;
}
//fast way to calculate modular power
ll power(ll n, ll e){
ll r = 1;
for(; e > 0; e >>= 1, n = (n*n) % M)
if(e&1) r = (r * n) % M;
return r;
}
//function to calculate de initial hash
//H(s) = s[0] * B^0 + s[1] * B^1 + ...
ll H(char sub[], int s){
ll h = 0;
for(ll i = 0; i < s; i++)
h = mod(h + mod(power(B, i) * sub[i]));
return h;
}
//brute force comparing when hashes match
bool check(char text[], char sub[], int ini, int s){
int i = 0;
while(text[ini + i] == sub[i] && i < s) i++;
return i == s;
}
//all together here
void RabinKarp(char text[], char sub[]){
int t = strlen(text), s = strlen(sub);
ll hs = H(sub, s), ht = H(text, s);
int lim = t - s;
for(int i = 0; i <= lim; i++){
if(ht == hs)
if(check(text, sub, i, s))
printf("MATCH AT %d\n", i);
ht -= text[i];
ht /= B;
ht = mod(ht + power(B, s - 1) * text[i + s]);
//we had text[i] * B^0 + text[i+1] * B^1 + ... + text[i + len - 1] * B^(len-1)
//then text[i+1] * B^1 + text[i+2] * B^2 + ... + text[i + len - 1] * B^(len-1)
//then text[i+1] * B^0 + text[i+2] * B^1 + ... + text[i + len - 1] * B^(len-2)
//finally we add a new last term text[i + len] * B^(len-1)
//so we moved the hash to the next position
}
}
int main(){
char text[] = "uvauvauvaaauva";
char sub[] = "uva";
char sub2[] = "uvauva";
RabinKarp(text, sub);
printf("----------------------------\n");
RabinKarp(text, sub2);
}
The problem is that after I take the modulus, the hash can become a small number and then, when I add some big factor to it, the hashes may not match even when they should.
For example: abc inside xabc
when I take the hash of abc and xab, suppose both of them are bigger than the modulus, so they get small after the modulus operation.
Then, when I remove 'x' and add the 'c' factor, the sum can be smaller than the modulus but still big, so it won't match.
How can I overcome this problem?
ht /= B;
is not plausible. First of all because you are doing arithmetic mod M, and the modular equivalent of division is not the same as the standard one. Secondly because you should expect the same answer for x and x + M and this will not be the case.
You have text[i] * B^0 + text[i+1] * B^1 + ... + text[i + len - 1] * B^(len-1)
If you work with
text[i] * B^(len-1) + text[i+1] * B^(len - 2) + ... + text[i + len - 1] * B^0
You can subtract off text[i] * B^(len-1) and then multiply by B instead

Running Time of Nested Loops

I am sure the running time of this nested loop is O(N*log(N)). The running time of the inner loop is log(N) and the outher loop is N.
for (int i = 0; i < N; ++i) {
for (int j = 1; j <= i; j *= 2) {
}
}
In the inner Loop what if I change j *= 2 to j *= 3. How is the result going to change in this case?
#Kevin is completely right, but I thought I would show some experimental results. You can easily test this out by creating a counter that gets incremented inside each inner loop iteration and running for different values of N. Then a fit can be made of the form time = a * N * log(N). For the case j *= 2, we get a coefficient a = 1.28. For j *= 3, we get a = 0.839.
I generated this figure using the MATLAB script below:
clear
clc
close all
nmin = 10;
nmax = 1000;
count1 = zeros(nmax - nmin + 1, 1);
for n = nmin: nmax
k = 0;
for i = 0: n - 1
j = 1;
while (j <= i)
j = j * 2;
k = k + 1;
end
end
count1(n - nmin + 1) = k;
end
ns = (nmin: nmax)';
figure
hold on
plot(ns, count1, '--')
a1 = mean(count1 ./ (ns .* log(ns)))
fit1 = a1 * ns .* log(ns);
plot(ns, fit1)
%%
count2 = zeros(nmax - nmin + 1, 1);
for n = nmin: nmax
k = 0;
for i = 0: n - 1
j = 1;
while (j <= i)
j = j * 3;
k = k + 1;
end
end
count2(n - nmin + 1) = k;
end
ns = (nmin: nmax)';
plot(ns, count2, '-.')
a2 = mean(count2 ./ (ns .* log(ns)))
fit2 = a2 * ns .* log(ns);
plot(ns, fit2)
xlabel('N')
ylabel('Time complexity')
legend('j *= 2', 'j *= 2 fit', 'j *= 3', 'j *= 3 fit', 'Location', 'NorthWest')
It will still be logarithmic. However, it will be scaled by a constant factor (which is irrelevant in Big O analysis).
The effect is that the base of the logarithm changes (see https://en.wikipedia.org/wiki/Logarithm#Change_of_base).
----------[ j = 2 * j ] for j < i:-------------
j = 2*1 = 2 =>2^1
2*2 = 4 =>2^2
2*4 = 8 =>2^3
............. 2^k = n say n==i
if log applied on both side 2^k = n
log(2^k) = logn
k = log_2(N) where 2 is the base
----------[ j = 3 * j ] for j < i:-------------
j = 3*1 = 3 =>3^1
3*3 = 9 =>3^2
3*9 = 27 =>2^3
.............loop stop when 3^k = n say n==i
if log applied on both side 3^k = n
log(3^k) = logn
k = log_3(N) where 3 is the base

Resources