If you find all divisors(including the primes) of n are say a,b,c,d...h. If a divisor h > sqrt(n) exists, then some divisor c must also exist such that h * c = n and since h > sqrt(n) and h * c = sqrt(n) * sqrt(n) c < sqrt(n). So,...

algorithm,math,time-complexity,computer-science,recurrence-relation

Here are a few hints : define R(n) = T(n)/(n-1)! solve the recurrence for R(n) express T(n) as a function of R(n) ...

So your initial approach is something like x.group_by { | e | e[:a] }.values.inject(&:zip).flatten It fails if a group has less elements than an earlier group. The idea is to switch them if the first array is too short (afterwards remove the nils with compact): x.group_by { | e |...

python,algorithm,decorator,python-decorators,rate-limiting

You can use a threading.Semaphore to count and block the requests that are exceeding the limit, in combination with threading.Timer to schedule a function that releases the semaphore. from threading import Semaphore, Timer from functools import wraps def ratelimit(limit, every): def limitdecorator(fn): semaphore = Semaphore(limit) @wraps(fn) def wrapper(*args, **kwargs): semaphore.acquire()...

algorithm,directed-acyclic-graphs

Finding longest path in a DAG doesn't really "care" about only positive weights, it is done using Dynamic Programming (DP) by following the formula: D(target) = 0 D(i) = max { D(j) + w(i,j) | for each edge (i,j) } The above is finding D(v), which is the maximal length...

javascript,arrays,algorithm,recursion,matrix

Your code is very close but it is doing more than it needs to do. Here I simplify and bug fix: var input = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]; var spiralTraversal = function(matriks){ var result = []; var goAround...

php,regex,algorithm,compare,pattern-matching

As @CasimiretHippolyte commented, regex is the better means as word boundaries can be used. Further caseless matching is possible using the i flag. Use with preg_match_all return value: Returns the number of full pattern matches (which might be zero), or FALSE if an error occurred. The pattern for matching one...

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....

It's possible in a variant of B+ tree called PO-B+ tree. In this "preparatory operations B+ tree" the number of keys in a node may be between n-1 and 2n+1 rather than n and 2n in the usual B+-tree (quoted from the paper). For delete operation (called PO-delete in the...

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),...

algorithm,recurrence,recurrence-relation

For case (ii) we are finding a subset of {x1,..,xj} that uses xj and sums to i. However, we are making this sum by combining xj with a subset of {x1,..,x(j-1)}. If we had p(i-xj,j) then we would be saying that we can make a total of i by using...

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...

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}: //...

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...

If you only need to do this once, or speed is not really important, and your trace doesn't tend to loop back on itself so that detecting the closest two points could differ from detecting the line segment between them, then it's pretty easy. First, you need a distance squared...

You have n possible problems, and each one can either be included or excluded from the problem set. This means that there are 2 options for every problem, so with n problems there are 2^n options for creating possible problem sets. With the line for(i=0; i<(1<<n); i++) you are iterating...

algorithm,social-networking,igraph

I think Newman's algorithm meets your requirements. It works by computing "network modularity" and then splitting the network into two groups. After that it recursively applies the same principle to the newly formed groups until no further increase in modularity is possible. It should also be implemented in igraph. At...

Work your way down. Start at the target number and try to get it to 0. The only way to get an odd target number is to add one to an even number, so if you ever see an odd number, +1 must be the operation used to get that...

You can do what you want with division and remainder: uint first_variable = version / 1000000; uint second_variable = (version / 1000) % 1000; uint third_variable = version % 1000; / 1000000 will shift the number 6 digits to the right, discarding all the rightmost digits, and % 1000 will...

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....

I am pretty sure this algorithm is as efficient and easier to understand than your linked algorithm. The strategy here is to understand that the only way to make a number bigger without increasing its number of 1's is to carry a 1, but if you carry multiple 1's then...

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...

The reason why you're getting the wrong result is because the basic approach is missing a few moving pieces. You're not tracking all the information that you need to calculate this. Not only you need to track which characters you have seen, but also at which position in the string...

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...

c++,algorithm,matrix,divide-and-conquer

Here is the corrected source code. I have added some comments so you can follow it. Furthermore, I switched to a dynamic array of the correct size. #include<fstream> #include<conio.h> #include<iostream> using namespace std; int countOccurences(int** values, int min1, int min2, int max1, int max2, int searchValue) { if (min1 >...

algorithm,graph,graph-algorithm

If you allow preprocessing, there is a fast method: Construct the bridge-block forest, whose vertices are 2-connected components, and whose edges are bridges. (It's a tree if the graph is connected.) When you add an edge, if this connects points in the same 2-connected component, nothing happens. If you connect...

To me it looks the same as in the theory before. The trick is that they do it in small steps (constructing the polynomial) Consider a very simple example of a string of length 3: We initialize ht = 0. The loop will first get position 0: ht = text[0]...

You can find it easily by searching the string S in S+S. The first index you find is the cycle number you want (may be the entire string). In python it would be something like: In [1]: s = "abaabaabaabaaba" In [2]: print (s+s).index(s, 1) 3 The 1 is there...

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...

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) {...

(Am adding an additional answer, since 1) the focus of the first answer was using ready STL components, and 2) Howard Hinnant raised some interesting points since.) Thanks to Howard Hinnant for the principle of benchmarking the different approaches (as well as a very unique solution)! It has led to...

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...

algorithm,language-agnostic,job-scheduling,greedy

In fact, neither "earliest deadline first", "highest profit first" nor "highest profit/duration first" are correct algorithm... Assume 2 jobs: Job A has profit 1, time duration 1, deadline before day 1; Job B has profit 2, time duration 2, deadline before day 2; Then "earliest deadline first" fails to get...

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...

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...

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,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...

c++,algorithm,data-structures,disjoint-sets,disjoint-union

Each union operaiton on two items a,b in Disjoint Set Data Structure has two possible scenarios: You tried to unite items from the same set. In this case, nothing is done, and number of disjoint sets remain the same. You united items from two different sets, so you basically converged...

python,algorithm,data-structures

Following points need to apply code: Define lower and upper limit outside of for loop becsue if we define inside while loop, every time lo and hi variable will create with 0 and 100 value respectively. Give variable name according to variable work. lower = 0 higher = 100 God...

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,time,complexity-theory,master,theorem

Every time you solve a subproblem, you have to divide the current instance into more subproblems (cost = 100 steps). Then, you have to merge the results of the subproblems (cost = 75n steps). That means f(n) = 75n + 100 because f(n) represents the cost of solving a single...

java,algorithm,bit-manipulation

All you need really is this: public int updateBits(int n, int m, int i, int j) { int mask = ((int)((1L<<(j-i+1))-1))<<(i); return (n&~mask)|((m<<i)&mask); } Note that for debugging purpose, you can use following method to print out the bit string: System.out.println(Integer.toBinaryString(mask)); Basically I need to create a mask that matches...

algorithm,data-structures,tree,binary-tree,binary-search-tree

Rather than jumping right into an algorithm that works here, I'd like to give a series of observations that ultimately leads up to a really nice algorithm for this problem. First, suppose that, for each node in the tree, you knew the value of the largest and smallest values in...

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...

java,algorithm,data-structures,graph-algorithm

The approach that comes to mind could be to keep an ordered list of the orders and perform a binary search for the limit amount. All orders before that point in the ordered list will be less than the limit amount. // Generate a random array of numbers Random r...

python,algorithm,function,recursion

Just sort on the last column: sorted(f,key=lambda x: int(x.split(",")[-1])) You can use bisect to find where to put the new data to keep the data ordered after it is sorted once: from bisect import bisect import csv with open("foo.txt") as f: r = list(csv.reader(f)) keys = [int(row[-1]) for row in...

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...

javascript,algorithm,comparison,func

Can't you create a lookup object which holds all the multiplication factors? Think of this as if it were a two-dimensional table: var factors = { a: { b: 16, c: 32, d: 64, e: 256 }, b: { c: 18, d: 20, e: 64, f: 256 } }; Then...

Your reasoning looks sound to me. LINQs Except() iterates over the first collection putting it into a HashSet before iterating over the second collection, performing lookups against the HashSet - it is O(n + m). Your extension method is therefore O(n + m) too. As you mention, if you want...

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...

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;...

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);...

You can use LinkedList as queue: public static List<Object> list(Object... args) { return Arrays.asList(args); } public static List<Object> flattenNonRecursive(List<Object> list) { List<Object> result = new ArrayList<>(); LinkedList<Object> que = new LinkedList<>(list); while (que.size() > 0) { Object e = que.remove(); if (e instanceof List<?>) que.addAll(0, (List<?>)e); else result.add(e); } return...

Integer examples are for 32 bit int arithmetics, DWORD is 32bit unsigned int floating pow(x,y)=x^y is usually evaluated like this: How Math.Pow (and so on) actualy works so the fractional exponent can be evaluated: pow(x,y) = exp2(y*log2(x)) this can be done also on fixed point fixed point bignum pow integer...

The need for back-tracking in the knights tour problem is critical. The fact that you have not implemented your back-tracking in your code is the main reason why it does not work. To fix it you must at least clear the position at the end of your method. I.e when...

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,...

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...

arrays,string,algorithm,file,data-structures

For instance a single string matching is the z-algorithm. It's the fastest matcher.

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"...

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...

algorithm,optimization,bin-packing

If the problem under consideration is the generalized assignment problem, it is NP-hard but admits an approximation algorithm. From a brief look, the approximation ratio depends on the approximation ratio of an approximation algorithm for the knapsack problem, which in turn admits a fully polynomial time approximation scheme. In total....

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....

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...

c++,algorithm,dynamic-programming

Why can't we use a similar approach in this question? It won't work because in the n stairs problem, the order is important. For e.g. if you are climbing 5 stairs, {1, 2, 1, 1} is counted as different to {1, 1, 2, 1}. However in the making change...

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....

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...

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...

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]...

You can use a O(n^2) method with some pruning, which will make the program like O(nlogn) :) Declare two variable low = maximum value which position is less than k and high = lowest value which position is greater than k Keep track of the low and high value you...

javascript,node.js,algorithm,geojson,topojson

To compute the overlapping percentage Compute the intersection of the two polygons Intersection = intersect(Precinct, Block) Divide the area of Intersection by the area of the parent polygon of interest. Overlap = area(Intersection) / area(Parent) It is a little unclear what you mean by the percent overlap. The parent polygon...

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,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...

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.

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...

You forgot to move the index of the solution array when you recurse. generatePartitions(solution, number, sum, partitions + 1, solution[partitions]); becomes: generatePartitions(solution, number, sum, partitions + 1, solution[partitions-1]); Coliru link: http://coliru.stacked-crooked.com/a/83b0418e1b1c9bc1 Also, I'd propose using some form of std::pair<int,int> and a binary tree of some sort to do this for...

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...

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,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...

Something like this? (compile with gcc test.c -lm) #include <stdio.h> #include <math.h> int main(void) { int i, j; int n = 4; int m = (int)pow(2,n); int p = 5; for(i = 1; i <= n; i++) { for(j = (int)pow(2,i-1); j < ((int)pow(2,i)); j++) { if(j == p) {...

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 =...

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' :...

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....

You can try to simplify polyline, constructed from given points, with Douglas-Peucker algorithm, then build some kind of smooth curve through reduced point set. To make smooth curve, you can use splines (e.g. Catmull-Rom) or this approach (intended for closed curves, but might be adapted for open ones)...

php,algorithm,static-variables

Obviously, you can't output something before you know it. What you can do is store your output until you're done (using ob_start()), and then go through and clean up afterward. ...

In my opinion you can solve it using integer programming techniques. https://en.wikipedia.org/wiki/Integer_programming There are many free solvers out there. The model is simple. You have 20x100 variables that can be 0 or 1. Every variable x_{i,j} means (0: file not in this file system, 1: file in this file system)....

algorithm,vba,function,find,fuzzy-search

Try this out, I think it will find the best match Function FuzzyFind2(lookup_value As String, tbl_array As Range) As String Dim i As Integer, str As String, Value As String Dim a As Integer, b As Integer, cell As Variant Dim Found As Boolean b = 0 For Each cell...

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...

Very brief sketch of a linear-time solution: for each array element, compute the size of the maximal group for which that element is the minimum. (Break ties by treating the first of two equal elements as lesser.) Sort the elements by their associated size, in linear time using a degenerate...

algorithm,graph,graph-algorithm,linear-programming,np-complete

It's possible to formulate this as the following problem. Suppose each vertex v in the graph has weight w(v). You define a variable x(v), and use some out-of-the-box linear programming solver to solve max \sum_v w(v) x(v) (maximize the weight of chosen vertices) subject to x(u) + x(v) <= 1,...

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...

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] << " "; }...

It seems to me that you need to: Find the cycles in your graph Eliminate all edges that contribute to a cycle ...

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...

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,...

I think your program is failing because you need to change: _getAvailableID(i) to return _getAvailableID(i) (At the moment the recursive function finds the correct answer which is discarded.) However, it would probably be better to simply put all the ids you have seen into a set to make the program...

The usual idea is to loop over sorted ranges. This, you can bring down the brute-force O(N^2) effort to usually O(N log N). Here is an algorithm for that in pseudo code (maybe I'll update later with real C++ code): Sort both arrays Loop over both simultaneously with two iterators:...

python,arrays,algorithm,dynamic-arrays

Assuming that you are allowed to know the length of the array in advance and store a counter the following works: def remove_element(value,array): shift = 0 for index in xrange(len(array)): try: array[index] = array[index + shift] while array[index] == value: shift += 1 array[index] = array[index + shift] except IndexError:...

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)....

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...