How do I write the formula correctly in my comments? - comments

I want to write this formula in comments:
And this is how I wrote the formula in comments:
// based on formula S = n/2 * (a + (a*n))
However if I'm comparing the comments with the formula then it's missing the Sn, a1 and the an part.
My question is: how do I write the formula correctly in my comments?

You should use a multi-line comment in your the code before the function or the code. for example:
/*
* Formula to calculate sum of n numbers
* S = n/2 * (a + l)
* where S is the sum of n elements
* n is the number of elements
* a is the first element in the series
* l is the nth element in the series
*/

Related

Finding product of Absolute Difference of Every pair of integer from an array

Given an array, find the product of the absolute difference of every pair of integers.
For example: Given a[]= {2,3, 5, 7 };
output would be (3-2) * (5-2) * (7-2) * (5-3) * (7-3) * (7-5) = 240.
Can it be done better than O(n^2) ?
Edit:
All elements are distinct.
If you had to compute the sum of the absolute differences, then this would be your solution
Basically, if you take an arbitrary number, let's name it x, then you have it
m * x - n * x,
where m is the number of items which are smaller than x and n is the n number of items, which are greater than x. So, if for some reason you had a sorted array, then the index of each item would directly tell you how many greater or smaller items are if it's unique in the array. If not, then you can determine the number of higher and lower elements as well.
So, if the array is sorted, than computing the result is linear. Sorting the array if it's completely unsorted is n * log(n) of complexity if you use mergesort. Hence, the complexity is
O(n + n * log(n)) = (n + 1)log(n)
But for the product of absolute differences
you have a product of the form of
(a1 - b1) * ... (...)
since you have a product of subtractions, in order to find a pattern that you could use to optimize, you need more information about your data. The input that you have seem to contain primes. The product of
(a1 - b1) * (a2 - b2)
is
a1a2 - a1b2 - b1a2 + b1b2
I do not know about any pattern that you could use for your optimization, so I think this has an O(n^2) complexity.

How to group numbers by size

I have n different numbers and I want to sort them into k groups, such that any number in group 1 is smaller than any number in group 2, and anyone in group 2 smaller than anyone in group 3 and so on until group k (the numbers do not have to be sorted inside each group). I'm asked to design an algorithm that runs in O(n log k), but I can only come up with O(n^2) ones.
How can I do this?
You could achieve this by modifying the Bucket sort algorithm, below I have included a JavaScript implementation, see Github for further details on the source code. This implementation uses 16 buckets, you will have to modify it to allow for k buckets and you can omit the sorting of buckets itself. One approach would be to use 2^p buckets where p is the smallest integer that satisfies 2^p < n. This algorithm will run in O(n log k)
// Copyright 2011, Tom Switzer
// Under terms of ISC License: http://www.isc.org/software/license
/**
* Sorts an array of integers in linear time using bucket sort.
* This gives a good speed up vs. built-in sort in new JS engines
* (eg. V8). If a key function is given, then the result of
* key(a[i]) is used as the integer value to sort on instead a[i].
*
* #param a A JavaScript array.
* #param key A function that maps values of a to integers.
* #return The array a.
*/
function bsort(a, key) {
key = key || function(x) {
return x
};
var len = a.length,
buckets = [],
i, j, b, d = 0;
for (; d < 32; d += 4) {
for (i = 16; i--;)
buckets[i] = [];
for (i = len; i--;)
buckets[(key(a[i]) >> d) & 15].push(a[i]);
//This implementation uses 16 buckets, you will need to modify this
for (b = 0; b < 16; b++)
//The next two lines sort each bucket, you can leave it out
for (j = buckets[b].length; j--;)
a[++i] = buckets[b][j];
}
return a;
}
var array = [2, 4, 1, 5, 3];
$('#result').text(bsort(array, function(x) {
return x
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
Note that the problem statement is to separate n different numbers into k groups. This would get more complicated if there were duplicates as noted in the wiki links below.
Any process that can determine the kth smallest element with less than O(n log(k)) complexity could be used k-1 times to produce an array of the elements corresponding to the boundaries between k groups. Then a single pass could be made on the array, doing a binary search of the boundary array to split up the array into k groups with O(n log(k)) complexity. However, it seems that at least one algorithm to find the kth smallest element also partitions the array, so that alone could be used to create the k groups.
A unordered partial sort using a selection algorithm with worst case time O(n) is possible. Wiki links:
http://en.wikipedia.org/wiki/Selection_algorithm
http://en.wikipedia.org/wiki/Selection_algorithm#Unordered_partial_sorting
http://en.wikipedia.org/wiki/Quickselect
http://en.wikipedia.org/wiki/Median_of_medians
http://en.wikipedia.org/wiki/Soft_heap#Applications
Use K-selection algorithm with partition function from QuickSort - QuickSelect.
Let's K is power of 2 for simplicity.
At the first stage we make partition of N elements, it takes O(N) ~ p* N time, where p is some constant
At the second stage we recursively make 2 partitions of N/2 elements, it takes 2* p* N/2 = p*N time.
At the third stage we make 4 partitions of N/4 elements, it takes 4*pN/4 = pN time.
...
At the last stage we make K partitions of N/K elements, it takes K* p* N/K = p*N time.
Note there are Log(K) stages, so overall time is Log(K) * p * N = O(N*Log(K)
Thank you for all your help, basically a quickselect (or any linear time sorting algorithm that finds the k-th statistic in linear time is enough) and, after running it k-1 times, we make a binary search over the original array to split the elements into groups, getting O(nlog k).
Also, if you don't want to make a binary search, in the quickselect, you can also separate the elements and find the statistic in each subset! #rcgldr, #MBo thank you for your ideas!

Algorithm Big Omega

I am having trouble analyzing the following.
for b = 1 to n
for u = b to n
for i = b to u
Print
I am having trouble determining the worst-case runtime.
The first loop runs n times, the second loop runs (n(n+1))/2 times.
I then beleive that the third loop runs (n+1)/2 times.
However I have been told that it has a runtime of O(n^3).
Therefore it's best-case runtime can't be greater then the worst-case runtime!
I'm hoping for a push in the right direction if possible!
Thanks!
The third loop executes Print u-b+1 times {3} when it is activated.
When the second loop is activated, the third loop is activated for all u from b to n, i.e. executes Print 1+2+3+...n-b+1 times (substitute u=1, 2, 3...n in {3}). Using the formula for triangular numbers, this count equals (n-b+1)(n-b+2)/2 {2}.
When the first loop is activated, the second loop is activated for all b from 1 to n, i.e. executes Print n(n+1)/2 + (n-1)n/2 + (n-2)(n-1)/2 + ... 1 times (substitute b= 1, 2, 3... n in {2}; the counts are decreasing).
Using the formula for tetrahedral numbers, this equals n(n+1)(n+2)/6 {1}.
If you have trouble with this approach, you can simulate the Prints by hand instead.
For n=1
*
For n=2
*
* *
*
For n=3
*
* *
* * *
*
* *
*
For n=4
*
* *
* * *
* * * *
*
* *
* * *
*
* *
*
...
You clearly see the pattern of triangles of decreasing size. The area of the triangles grows as the square of the side. The total volume grows as the cube of the side.

Improving inverse modulo via Euclidean algorithms

Stuck with a question for Complexity class: "You are given a,b in Z_N* and want to complete a^-1 and b^-1 mod N. By now we know how to calculate it via using the Euclidean algorithm twice, with a,N and b,N. My question is that how can one do it with a single invocation of the Euclidean Algorithm (Finding the GCD) and 3 multiplications mod N?
We know the following (all congruences mod N)
a * b * (a * b)^-1 = 1
b * (a * b)^-1 = a^-1
a * (a * b)^-1 = b^-1
So if we calculate (a * b)^-1, the partial inverses a^-1 and b^-1 can be calculated with a multiplication.

Understanding How Many Times Nested Loops Will Run

I am trying to understand how many times the statement "x = x + 1" is executed in the code below, as a function of "n":
for (i=1; i<=n; i++)
for (j=1; j<=i; j++)
for (k=1; k<=j; k++)
x = x + 1 ;
If I am not wrong the first loop is executed n times, and the second one n(n+1)/2 times, but on the third loop I get lost. That is, I can count to see how many times it will be executed, but I can't seem to find the formula or explain it in mathematical terms.
Can you?
By the way this is not homework or anything. I just found on a book and thought it was an interesting concept to explore.
Consider the loop for (i=1; i <= n; i++). It's trivial to see that this loops n times. We can draw this as:
* * * * *
Now, when you have two nested loops like that, your inner loop will loop n(n+1)/2 times. Notice how this forms a triangle, and in fact, numbers of this form are known as triangular numbers.
* * * * *
* * * *
* * *
* *
*
So if we extend this by another dimension, it would form a tetrahedron. Since I can't do 3D here, imagine each of these layered on top of each other.
* * * * * * * * * * * * * * *
* * * * * * * * * *
* * * * * *
* * *
*
These are known as the tetrahedral numbers, which are produced by this formula:
n(n+1)(n+2)
-----------
6
You should be able to confirm that this is indeed the case with a small test program.
If we notice that 6 = 3!, it's not too hard to see how this pattern generalizes to higher dimensions:
n(n+1)(n+2)...(n+r-1)
---------------------
r!
Here, r is the number of nested loops.
The 3rd inner loop is the same as the 2nd inner loop, but your n is a formula instead.
So, if your outer loop is n times...
and your 2nd loop is n(n+1)/2 times...
your 3rd loop is....
(n(n+1)/2)((n(n+1)/2)+1)/2
It's rather brute force and could definitely be simplified, but it's just algorithmic recursion.
The mathematical formula is here.
It is O(n^3) complexity.
This number is equal to the number of triples {a,b,c} where a<=b<=c<=n.
Therefore it can be expressed as a Combination with repetitions.. In this case the total number of combinations with repetitions is: n(n+1)(n+2)/6
1 + (1+2) + (1+ 2+ 3 ) +......+ (1+2+3+...n)
You know how many times the second loop is executed so can replace the first two loops by a single one right? like
for(ij = 1; ij < (n*(n+1))/2; ij++)
for (k = 1; k <= ij; k++)
x = x + 1;
Applying the same formula you used for the first one where 'n' is this time n(n+1)/2 you'll have ((n(n+1)/2)*(n(n+1)/2+1))/2 - times the x = x+1 is executed.

Resources