I need to formal proof that below algorithm return 1 for n = 1 and 0 in other cases.

```
function K( n: word): word;
begin
if (n < 2) then K := n
else K := K(n − 1) * K(n − 2);
end;
```

Anyone could help? Thank you

I need to formal proof that below algorithm return 1 for n = 1 and 0 in other cases.

```
function K( n: word): word;
begin
if (n < 2) then K := n
else K := K(n − 1) * K(n − 2);
end;
```

Anyone could help? Thank you

This can be proven by induction, but as previous posters have shown, it's tricky to get formally correct when referring to `K`

directly in the proof.

Here's my suggestion: Let *P*(*n*) be the property we want to show:

*P*(*n*) holds iff *K*(*n*) yields 1 for *n* = 1, and 0 for *n* ≠ 1.

Now we can clearly express what we want to show: Ɐ*n*.*P*(*n*)

**Base case:***n*≤ 2Trivial check by case analysis:

*P*(0) is ok, since*K*(0) = 0

*P*(1) is ok, since*K*(1) = 1**Induction hypothesis:***P*(*n*) holds for all 2 ≤*n*<*c*.**Inductive step:**Show that*P*(*c*) holds- By definition of
*K*we have*K*(*c*) =*K*(*c*-1) ×*K*(*c*-2) - By the induction hypothesis, we know that
*P*(*c*-1) and*P*(*c*-2) hold. - Since at most one of
*K*(*c*-1) and*K*(*c*-2) can be 1 (and the other must be 0) the product is 0. - Which means that
*P*(*c*) holds

- By definition of

Qed.

Your logic does not work if(i%(ans%i)==0)ans*=(i/(ans%i)); else ans*=i; For example, if ans = 10 and i = 14, so, the lcm should be 70, but in your code, it is 140. The reason is, between ans and i , there are common divisors, but your code cannot detect that. For...

I would go with performing Arithmetic Right Shift(till the length of the binary number) two at a time. This >> used in my logic is for arithmetic shift. (Note: In C language, right shifts may or may not be arithmetic!) Like, int count=0; bit=extractLastbit(binary_representation_of_the_number); while(count!=binaryLength){ // binaryLength is the length...

To clarify @Dan Getz and add @collapsar answer I will add the following: Dan's Formula is correct: (score1 * weight1 + ... + scoreN * weightN) / (weight1 + ... + weightN) The beauty of the weighted average is you get to choose the weights! So we choose days since...

algorithm,recursion,permutation

A common approach is as follows. If you have, say, K bins, then add K-1 special values to your initial array. I will use the -1 value assuming that it never occurs in the initial array; you can choose a different value. So for your example the initial array becomes...

undefined is not a boolean value so when you use ! operator, your value will be converted to boolean at first. but == operator just checking your values. so if you want to get true from undefined == false you should do it like Boolean(undefined) == false ? 't' :...

php,algorithm,assign,subgraph,pairing-heap

So I finally found a valid way to achieve what was described in before. The solution: We make a column for each slot that is possibly given away. A cours has a amount of slots. We should have a number of columns, which is the sum of each amount of...

This would be a hard real-time system - if a deadline is missed then a patient might die. As such, Algorithm B is the preferred algorithm because you can design the hardware around the n^2 worst case, whereas with Algorithm A the hardware must account for the n^4 worst case...

See I know you will feel bad when I will tell you what is wrong in your answer. But the only thing wrong is you using gets(). Its 2015 no one uses it. I changed that to a scanf statement i.e delete this part of your code and get(s); get(s);...

Assume task 0 finishes at day 0. Add a new column to your table, "completion day". Go down the list of tasks, add the duration of the current task onto the completion day of the task it is dependent on. Store that as the current task's completion day. Find the...

Consideration fib( 4) = fib( 2) = 1 * fib(2) fib( 6) = fib( 4) + fib( 2) = 2 * fib(2) fib( 8) = fib( 6) + fib( 4) = 3 * fib(2) fib(10) = fib( 8) + fib( 6) = 5 * fib(2) fib(12) = fib(10) + fib(...

python,regex,algorithm,python-2.7,datetime

What about fuzzyparsers: Sample inputs: jan 12, 2003 jan 5 2004-3-5 +34 -- 34 days in the future (relative to todays date) -4 -- 4 days in the past (relative to todays date) Example usage: >>> from fuzzyparsers import parse_date >>> parse_date('jun 17 2010') # my youngest son's birthday datetime.date(2010,...

IIUC, this is the classic Minimum Vertex Cover problem, which is, unfortunately, NP Complete. Fortunately, the most intuitive and greedy possible algorithm is as good as it gets in this case....

Here is the graph I propose: Two kinds of vertices: departure vertex: airport+departure time arrival vertex: airport + arrival time. Two kind of edges: flight edge: from a departure vertex to an arrival vertex wait edge: from an arrival vertex to a departure vertex of later time in the same...

algorithm,numerical-methods,numerical,numerical-integration

numerical integration always return just a number if you do not want the number but function instead then you can not use numerical integration for this task directly Polynomial approach you can use any approximation/interpolation technique to obtain a polynomial representing f(x) then integrate as standard polynomial (just change...

Big O,Theta or Omega notation all refer to how a solution scales asymptotically as the size of the problem tends to infinity, however, they should really be prefaced with what you are measuring. Usually when one talks about big O(n) one usually means that the worst case complexity is O(n),...

c++,algorithm,inheritance,time-complexity

The first is supposedly in O(M*logN) time, where M is the size of the list, and N = number of concrete derived classes of Base It's not though. unordered_map is a hashtable, lookup and insertion have constant complexity on average. So the first is still O(M). Just with more...

Let's say the domain is as following String domain[] = { a, b, .., z, A, B, .. Z, 0, 1, 2, .. 9 }; Let's say the password size is 8 ArrayList allCombinations = getAllPossibleStrings2(domain,8); This is going to generate SIZE(domain) * LENGTH number of combinations, which is in...

c++,algorithm,parallel-processing,c++14

Parallel prefix sum is a classical distributed programming algorithm, which elegantly uses a reduction followed by a distribution (as illustrated in the article). The key observation is that you can compute parts of the partial sums before you know the leading terms.

Basically, you are finding all permutations of the array using a recursive permutation algorithm. There are 4 things you need to change: First, start your loop from pos, not 0 Second, swap elements back after recursing (backtracking) Third, only test once you have generated each complete permutation (when pos =...

3. is indeed correct, as you will need to go through the algorithm and terminate at the "worst" stop clause, where the list is empty, needed log(n) iterations. 1. is not correct. The best case is NOT when the first element is the target, it is when the middle element...

c,algorithm,security,math,encryption

This is not a power operator. It is the XOR operator. The thing that you notice for the XOR operator is that x ^ k ^ k == x. That means that your encryption function is already the decryption function when called with the same key and the ciphertext instead...

algorithm,discrete-mathematics

The loops in fact only go up to the cube root of N. (i^3 < n, etc.) The 3 nested loops of this length, give O(cube root of N, cubed). This O(N) Of note, if you were correct and they each went to one third of N, then cubing this...

ruby,algorithm,search,recursion

The first time you enter the adjacencies[to_append].each, you immediately return from the method, therefore the loop will never be executed more than once. You need to return a list of phone numbers instead of just a single phone number build that list somehow in your recursive call ...

algorithm,optimization,dynamic-programming,frequency

There is no need for Dynamic Programming for this problem. It is a simple sorting problem, with a slight twist. Find frequency / length for each file. This gets you, how frequent is each unit length access for the file. Sort these in descending order since each file is "penalized"...

l = [1,'a',12,'b','poppy'] def p(l,t): return [l[i-1] for i in t] print(p(l,(3,4,5,2,1))) [12, 'b', 'poppy', 'a', 1] indexing is 0 based so if you actually wanted to use the indexes for a 5 element list it would be (2,3,4,1,0) and [l[i] for i in t]...

Consider the simpler problem of summing the first 100 positive integers: sum [x | x <- [1,2..], x <= 100] This doesn't work either. As a human, you know that once x <= 100 returns False, it will never return True again, because x is getting larger. But Haskell doesn't...

javascript,algorithm,recursion

I'm going to extend @georg's answer and provide a full implementation var additivePersistance = (function () { function sumOfDigits (n) { var ret = 0; n.toString().split('').forEach(function (i) { ret += parseInt(i, 10); }); return ret; } return function additivePersistance (n) { if (n < 10) { return 0; } return...

python,algorithm,time-complexity,longest-substring

It's O(N) 'why to use DP of O(N2)' : You don't need to for this problem. Note, though, that you take advantage of the fact that your sequence tokens (letters) are finite - so you can set up a list to hold all the possible starting values (26) and...

You may access out of bound memory while accessing key[counter] causing undefined behaviour. One possible fix is: for (int i = 0; i < s.size(); i++){ if (s[i] == key[counter]){ if(++counter == 5) break; // ^^ ^^^^ ^^^^^ } } or rewrite for as for (int i = 0; i...

algorithm,set,combinatorics,backtracking

You can try the recursive answer if your set is not to big (or else use stack) : The principle is the following, you have a function that give back : rec_func(SET) = List of List of Set And work as follow : rec_func(SET) = if SET = {empty}: //...

I think this should work for square matrices: void printHemisphere(int matrix[N][M], int n, int m) { int mid = n / 2; for(int i = 1; i < mid; i++) { for (int j = n - i; j < m; ++j) { std::cout << matrix[i][j] << " "; }...

algorithm,coordinates,coordinate-systems,coordinate

So here's my question: does this algorithm exists already? Has it a name? This mapping is called the Z-order curve or Morton code: In mathematical analysis and computer science, Z-order, Morton order, or Morton code is a function which maps multidimensional data to one dimension while preserving locality of...

c,string,algorithm,data-structures

Yes, this is in O(n) in the average and worst case, where n is the length of the shorter of both given strings. You could also express that as O(min(m,n)) with m and n being the lengths of both strings, respectively. But no, O(n) doesn't mean that it needs exactly...

c++,arrays,algorithm,recursion

Do a regular binary search but with the (array[i] == i) condition instead of searching for a particular value. If (array[i] > i) move left else move right Of course this requires the values to be sorted, but your example indicates that is the case....

Dijkstra should pass, I just make a submission using JAVA, and it took less than a second to complete each task. As I have mentioned, each value in the matrix can go up to 10^9, your solution can encounter a number overflow problem, which can effect the running time. My...

What's important to realize is that it's easy to take big steps: 1 digit numbers: 123456789 - 9 * 1 digit 2 digit numbers: 101112...9899 - 90 * 2 digits 3 digit numbers: 100101102...998999 - 900 * 3 digits 4 digit numbers: ... Now you can do a recursive solution...

c#,arrays,algorithm,random,cycle

What you are doing is generating a random permutation of size count. Then you check the properties of the permutation. If your random number generator is good, then you should observe the statistics of random permutations. The average number of cycles of length k is 1/k, for k<count. On average,...

java,algorithm,function,genetic-programming,convergence

I don't have the time to dig into your code but I'll try to answer from what I remember on GAs: Sometimes I will give it points that will never produce a function, or will sometimes produce a function. It can even depend on how deep the initial trees are....

The merge function is wrong, you did not consider when some part of a or b has leftover elements. void merge(int * a, int ac, int * b, int bc, int * out) { int i = 0, j = 0; while (i < ac && j < bc) {...

Here are my results so far: L=1-7: "aabbaba" -> "aabbabaa" (or the mirror, confirming your result) L=8: "aaabbaba" -> "aaabbabaa" (or the mirror) L=9: "aaaabbbaba" -> "aaaabbbabaa" (or the mirror) All futher L can be solved just by prefixing an additional a to the starting string....

algorithm,math,statistics,variance,standard-deviation

Given the forward formulas Mk = Mk-1 + (xk – Mk-1) / k Sk = Sk-1 + (xk – Mk-1) * (xk – Mk), it's possible to solve for Mk-1 as a function of Mk and xk and k: Mk-1 = Mk - (xk - Mk) / (k - 1)....

There exists a rather simple O(n) approach using the so-called "two pointers" or "two iterators" approach. The key idea is to have two iterators (not necessarily C++ iterators, indices would do too) running on the same array so that if first iterator points to value x, then the second iterator...

algorithm,dynamic-programming,knapsack-problem

One possibility would be to provide a suitable number of multiplicities of the items. For item i, there can be at most m_i := K / w_i choices of that item, where K denotes the knapsack capacity and w_i denotes the weight of the i-th item. Furthermore, for each weight...

java,c++,algorithm,recursion,dfs

In the line res.add(temp); temp is a reference. You are adding a reference to the same list (itemList) every time you add it. Try changing it to something list res.add(new ArrayList(temp)); so that it copies the list instead....

algorithm,scala,priority-queue

If your elements are Ints, the easiest way to define such an Ordering is by taking a negative of the elements which should be ordered in reverse. You can create the Ordering, using methods provided by the object Ordering, and pass it to the PriotityQueue either explicitly: // I'm using...

If and only if, at some point during kahn's algorithm has no source to choose (and the remaining graph is still none empty), there is a cycle Proof: Direction1 <--: If there is a cycle, let it be v1->v2->v3->vk->v1. At each step of the algorithm, none of v1,v2,...,vk is a...

algorithm,graph,tree,runtime,big-o

Don't know if your algorithm is correct, but it doesn't seem O(|V|) at least, because getting the "smallest edge not in T" of a vertex cannot be done in O(1). The most usual way to add an edge e=(u, v) into a MST T is: Run a BFS in T...

algorithm,graph,tree,runtime,big-o

Since everything is still connected and only one edge has been removed, then most (and maybe all) of the spanning tree remains the same. Attempt to construct the same minimum spanning tree, and if the edge that was removed was part of the spanning tree, grab the next smallest edge...

Try this, it worked for me with your example matrix. It looks like a lot of code, but there are functions just for the example and for debugging purpose. void disp( const std::vector< int >& a ) { for ( const auto item : a ) { std::cout << item;...

If you look at your inserstion sort As you already put count =1 because as for exits on exit condition of for loop. for same reason then it also make sense that when while loop cancels the count++ inside will not get executed but there was a comparison made. but...