Count of arrays having consecutive element with different values - combinations

Given two positive integers n , m . The task is to count the number of different array that can be formed of size n such that each element is between 1 to m and two consecutive element are different. Also, the first and last elements of each array should be same.
I/p O/p
3 3 --> 6
3 4 --> 12
4 4 --> 24
This is what I have got
If n == 3 output is m * (m - 1)
If n != 3 output is m * ((m - 1)^(n - 3)) * (2 * m - 3)
Explanation
At first place there are m choices.
From 2nd to (n - 2) places there is there are (m - 1) choices.
For (n - 1) place there are 2 cases:
1st is if (n - 2) and nth place are same then (m - 1) choices
2nd is if (n - 2) and nth place are not same then (m - 2) choices
So total (2 * m - 3) choices.
If I am wrong please correct me.

Related

How to calculate Primes number

I'm trying to solve programming question, a term called "FiPrima". The "FiPrima" number is the sum of prime numbers before, until the intended prime tribe.
INPUT FORMAT
The first line is an integer number n. Then followed by an integer number x for n times.
OUTPUT FORMAT
Output n number of rows. Each row must contain the xth "FiPrima" number of each line.
INPUT EXAMPLE
5
1 2 3 4 5
OUTPUT EXAMPLE
2
5
10
17
28
EXPLANATION
The first 5 prime numbers in order are 2, 3, 5, 7 and 13.
So:
The 1st FiPrima number is 2 (2)
The 2nd FiPrima number is 5 (2 + 3)
The 3rd FiPrima number is 10 (2 + 3 + 5)
The 4th FiPrima number is 17 (2 + 3 + 5 + 7)
The 5th FiPrima number is 28 (2 + 3 + 5 + 7 + 13)
CONSTRAINTS
1 ≤ n ≤ 100
1 ≤ x ≤ 100
Can anyone create the code ?

prime numbers algorithm efficiency

I have a question about prime numbers algorithm.
why in the following pseudo code i increases by 6 and not by 2 every iteration?
function is_prime(n)
if n ≤ 1
return false
else if n ≤ 3
return true
else if n mod 2 = 0 or n mod 3 = 0
return false
let i ← 5
while i * i ≤ n
if n mod i = 0 or n mod (i + 2) = 0
return false
i ← i + 6
return true
Thanks!
If it increased by 2 it would be testing almost everything twice, that wouldn't make any sense. So I assume you mean: how can it get away with not testing every odd number?
This is because every prime p greater than 3 is of the form 6n±1. Proof:
Consider the remainder r = p mod 6. Obviously r must be odd. Notice also that r cannot be 3, because then p would be divisible by 3, making it not a prime. This leaves only the possibilities 1 and 5, which correspond p being of the form 6n+1 or the form 6n-1 respectively.
The effect is that it avoid testing multiples of 3. Dividing by a multiple of 3 is redundant, because we already know that n is not a multiple of 3, so it cannot be the multiple of a multiple of 3 either.
The assignment in the loop body is i <- i + 6, not i <- i + 2. In the if statement the expression i + 2 just becomes a new value. There is no assignment operator in that expression.
The algorithm is based on the fact that prime numbers can be predicted using the formula 6k ± 1 and this does not apply on 2 and 3.
For instance
(6 * 1) - 1 = 5
(6 * 2) - 1 = 11
(6 * 3) - 1 = 17
The list goes on and on.

Decreasing Loop Interval by 1 in C/C++

Let's say I have 15 elements. I want to group them such a way that:
group1 = 1 - 5
group2 = 6 - 9
group3 = 10 - 12
group4 = 13 - 14
group5 = 15
This way I'll get elements in each group as below:
group1 = 5
group2 = 4
group3 = 3
group4 = 2
group5 = 1
As you can see loop interval is decreasing.
I took 15 just for an example. In actual programme it's user driven parameter which can be anything (hopefully few thousand).
Now what I'm looking for is:
Whatever is in group1 should have variable "loop" value 0, group2 should have 1, group3 should have 2 and so on... "loop" is an int variable which is being used to calculate some other stuff.
Let's put in other words too
I have an int variable called "loop". I want to assign value to it such a way that:
First n frames loop value 0 next (n -1) frames loop value 1 then next (n - 2) frames loop value 2 all the way to loop value (n - 1)
Let's say I have 15 frames on my timeline.
So n will be 5 ====>>>>> (5 + 4 + 3 + 2 + 1 = 15; as interval is decreasing by 1)
then
first 5 frames(1 - 5) loop is 0 then next 4 frames(6 - 9) loop is 1 then next 3 frames(10 - 12) loop is 2 then next 2 frames(13 - 14) loop is 3 and for last frame(15) loop is 4.
frames "loop" value
1 - 5 => 0
6 - 9 => 1
10 - 12 => 2
13 - 14 => 3
15 => 4
I've tried with modulo(%). But the issue is on frame 12 loop is 2 so (12 % (5 - 2)) remainder is 0 so it increments loop value.
The following lines are sample code which is running inside a solver. #loop is by default 0 and #Frame is current processing frame number.
int loopint = 5 - #loop;
if (#Frame % loopint == 0)
#loop += 1;
If I understand this correctly, then
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[]) {
int n = atoi(argv[1]);
for(int i = 1; i <= n; ++i) {
printf("%d: %f\n", i, ceil((sqrt(8 * (n - i + 1) + 1) - 1) / 2));
}
}
is an implementation in C.
The math behind this is as follows: The 1 + 2 + 3 + 4 + 5 you have there is a Gauß sum, which has a closed form S = n * (n + 1) / 2 for n terms. Solving this for n, we get
n = (sqrt(8 * S + 1) - 1) / 2
Rounding this upward would give us the solution if you wanted the short stretches at the beginning, that is to say 1, 2, 2, 3, 3, 3, ...
Since you want the stretches to become progressively shorter, we have to invert the order, so S becomes (n - S + 1). Therefore the formula up there.
EDIT: Note that unless the number of elements in your data set fits the n * (n+1) / 2 pattern precisely, you will have shorter stretches either at the beginning or in the end. This implementation places the irregular stretch at the beginning. If you want them at the end,
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[]) {
int n = atoi(argv[1]);
int n2 = (int) ceil((sqrt(8 * n + 1) - 1) / 2);
int upper = n2 * (n2 + 1) / 2;
for(int i = 1; i <= n; ++i) {
printf("%d: %f\n", i, n2 - ceil((sqrt(8 * (upper - i + 1) + 1) - 1) / 2));
}
}
does it. This calculates the next such number beyond your element count, then calculates the numbers you would have if you had that many elements.

Complexity of an algorithm with two recursive calls

I have a strange algorithm than is being called recursively 2 times. It's
int alg(int n)
loop body = Θ(3n+1)
alg(n-1);
alg(n-2)
Somehow i need to find this algorithm's complexity. I've tried to find it with using characteristic polynomial of the above equation but the result system is too hard to solve so i was wondering if there was any other straight way..
Complexity: alg(n) = Θ(φ^n) where φ = Golden ratio = (1 + sqrt(5)) / 2
I can't formally prove it at first, but with a night's work, I find my missing part - The substitution method with subtracting a lower-order term. Sorry for my bad expression of provement (∵ poor English).
Let loop body = Θ(3n+1) ≦ tn
Assume (guess) that cφ^n ≦ alg(n) ≦ dφ^n - 2tn for an n (n ≧ 4)
Consider alg(n+1):
Θ(n) + alg(n) + alg(n-1) ≦ alg(n+1) ≦ Θ(n) + alg(n) + alg(n-1)
c * φ^n + c * φ^(n-1) ≦ alg(n+1) ≦ tn + dφ^n - 2tn + dφ^(n-1) - 2t(n-1)
c * φ^(n+1) ≦ alg(n+1) ≦ tn + d * φ^(n+1) - 4tn + 2
c * φ^(n+1) ≦ alg(n+1) ≦ d * φ^(n+1) - 3tn + 2
c * φ^(n+1) ≦ alg(n+1) ≦ d * φ^(n+1) - 2t(n+1) (∵ n ≧ 4)
So it is correct for n + 1. By mathematical induction, we can know that it's correct for all n.
So cφ^n ≦ alg(n) ≦ dφ^n - 2tn and then alg(n) = Θ(φ^n).
johnchen902 is correct:
alg(n)=Θ(φ^n) where φ = Golden ratio = (1 + sqrt(5)) / 2
but his argument is a bit too hand-waving, so let's make it strict. His original argument was incomplete, therefore I added mine, but now he has completed the argument.
loop body = Θ(3n+1)
Let us denote the cost of the loop body for the argument n with g(n). Then g(n) ∈ Θ(n) since Θ(n) = Θ(3n+1).
Further, let T(n) be the total cost of alg(n) for n >= 0. Then, for n >= 2 we have the recurrence
T(n) = T(n-1) + T(n-2) + g(n)
For n >= 3, we can insert the recurrence applied to T(n-1) into that,
T(n) = 2*T(n-2) + T(n-3) + g(n) + g(n-1)
and for n > 3, we can continue, applying the recurrence to T(n-2). For sufficiently large n, we therefore have
T(n) = 3*T(n-3) + 2*T(n-4) + g(n) + g(n-1) + 2*g(n-2)
= 5*T(n-4) + 3*T(n-5) + g(n) + g(n-1) + 2*g(n-2) + 3*g(n-3)
...
k-1
= F(k)*T(n+1-k) + F(k-1)*T(n-k) + ∑ F(j)*g(n+1-j)
j=1
n-1
= F(n)*T(1) + F(n-1)*T(0) + ∑ F(j)*g(n+1-j)
j=1
with the Fibonacci numbers F(n) [F(0) = 0, F(1) = F(2) = 1].
T(0) and T(1) are some constants, so the first part is obviously Θ(F(n)). It remains to investigate the sum.
Since g(n) ∈ Θ(n), we only need to investigate
n-1
A(n) = ∑ F(j)*(n+1-j)
j=1
Now,
n-1
A(n+1) - A(n) = ∑ F(j) + (((n+1)+1) - ((n+1)-1))*F((n+1)-1)
j=1
n-1
= ∑ F(j) + 2*F(n)
j=1
= F(n+1) - 1 + 2*F(n)
= F(n+2) + F(n) - 1
Summing that, starting with A(2) = 2 = F(5) + F(3) - 5, we obtain
A(n) = F(n+3) + F(n+1) - (n+3)
and therefore, with
c*n <= g(n) <= d*n
the estimate
F(n)*T(1) + F(n-1)*T(0) + c*A(n) <= T(n) <= F(n)*T(1) + F(n-1)*T(0) + d*A(n)
for n >= 2. Since F(n+1) <= A(n) < F(n+4), all terms depending on n in the left and right parts of the inequality are Θ(φ^n), q.e.d.
Assumptions:
1: n >= 0
2: Θ(3n+1) = 3n + 1
Complexity:
O(2 ^ n * (3n - 2));
Reasoning:
int alg(int n)
loop body = Θ(3n+1)// for every n you have O(3n+1)
alg(n-1);
alg(n-2)
Assuming the alg does not execute for n < 1, you have the following repetitions:
Step n:
3 * n + 1
alg(n - 1) => 3 * (n - 1) + 1
alg(n - 2) => 3 * (n - 2) + 1
Now you basically have a division. You have to imagine a number tree with N as parent and n-1 and n-2 as children.
n
n-1 n-2
n - 2 n - 3 n - 3 n - 4
n - 3 n - 4 n - 4 n - 5 n - 4 n - 5 n - 5 n - 6
n-4 n-5 | n-5 n-6 |n-5 n-6 |n-6 n-7 n-5 n-6 n-6 n-7 n-6 n-6| n-6 n-8
It's obvious that there is a repetition pattern here. For every pair (n - k, n - k - 1) in A = {k, with k from 0 to n) except the first two and the last two, (n - 1, n - 2) and (n-2, n-3) there is a 3k + 1 * (2 ^ (k - 1)) complexity.
I am looking at the number of repetitions of the pair (n - k, n - k - 1). So now for each k from 0 to n I have:
(3k + 1) * (2 ^ (k - 1)) iterations.
If you sum this up from 1 to n you should get the desired result. I will expand the expression:
(3k + 1) * (2 ^ (k - 1)) = 3k * 2 ^ (k - 1) + 2 ^ (k - 1)
Update
1 + 2 + 2^2 + 2^3 + ... + 2^n = 2 ^ (n + 1) - 1
In your case, this winds up being:
2^n - 1
Based on the summation formula and k = 0, n . Now the first one:
3k * 2 ^ (k - 1)
This is equal to 3 sum from k = 0, n of k * 2 ^ (k - 1).
That sum can be determined by switching to polinomial functions, integrating, contracting using the 1 + a ^ 2 + a ^ 3 + ... + a ^ n formula, and then differentiated again to obtain the result, which is (n - 1) * 2 ^ n + 1.
So you have:
2 ^ n - 1 + 3 * (n - 1) * 2 ^ n + 1
Which contracted is:
2 ^ n * (3n - 2);
The body of the function takes Θ(n) time.
The function is called twice recursively.
For the given function the complexity is,
T(n) = T(n-1) + T(n-2) + cn ----- 1
T(n-1) = T(n-2) + T(n-3) + c(n-1) ----- 2
1-2 -> T(n) = 2T(n-1) - T(n-3) + c ----- 3
3 --> T(n-1) = 2T(n-2) + T(n-4) + c ----- 4
3-4 -> T(n) = 3T(n-1) - 2T(n-2) - T(n-3) - T(n-4) ----- 5
Let g(n) = 3g(n-1)
There for, we can approximate T(n) = O(g(n))
g(n) is Θ(3n)
There for T(n) = O(3n)

C++ - Circular array with lower/upper bounds?

I want to create something similar to a double linked list (but with arrays) that works with lower/upper bounds.
A typical circular array would probably look like:
next = (current + 1) % count;
previous = (current - 1) % count;
But what's the mathematical arithmetic to incorporate lower/upper bounds properly into this ?
0 (lower bound item 1)
1
2 (upper bound item 1)
3 (lower bound item 2)
4 (upper bound item 2)
So that:
-> next on index 2 for item 1 returns 0
-> previous on index 0 for item 1 returns 2
-> next on index 4 for item 2 returns 3
-> previous on index 3 for item 2 returns 4
Thank you !
NOTE: Can't use external libraries.
In general mathematical terms:
next === current + 1 (mod count)
prev === current - 1 (mod count)
where === is the 'congruent' operator. Converting this to the modulus operator, it would be:
count = upper - lower
next = ((current + 1 - (lower%count) + count) % count) + lower
prev = ((current - 1 - (lower%count) + count) % count) + lower
It would be up to you to find out the upper & lower bounds for each item. You could store this in a binary tree for fast retrieval. Maybe I'm not understanding your question.
(note that this assumes lower < upper, and lower > 0)
+=======+ +=======+ +=======+
| Obj | ---> | Obj | ---> | Obj |
buffer | 1 | <--- | 2 | <--- | 3 |
+=======+ +=======+ +=======+
index 0 1 2 /* our first run */
index 3 4 5 /* second run */
and so on ...
So, you see for a 3 member list, the 1st item is indexed by 0, 3, 6, etc. Similarly, the second item is indexed by 1, 4 (1 + 3), 7 (4 + 3), ...
The general rule is: next <- (next + 1) % size, where size = upper - lower + 1
Using this formula we get:
curr | next
-------+-----------------
0 | (0 + 1) % 3 = 1
-------+-----------------
1 | (1 + 1) % 3 = 2
-------+-----------------
2 | (2 + 1) % 3 = 0
-------+-----------------
Hope that helps
I wrote this article a few years back about a circular STL iterator.
http://noveltheory.com/Iterators/Iterator_N0.htm
It will work on any STL collection (vectors & boost:array, etc)
Boost has a Circular container that I believe you can set bounds on as well.
In fact the Example on that page looks very similar to what you are saying here.
But anyway, you could accomplish the math portion of it easily using a modulus:
So say your max was 3:
int MAX = 3;
someArray[ 0 % MAX ]; // This would return element 0
someArray[ 1 % MAX ]; // This would return element 1
someArray[ 3 % MAX ]; // This would return element 0
someArray[ 4 % MAX ]; // This would return element 1