How to represent Big O(n!) Time complexity from for loop? - big-o

For Example
O(n)
for (int i=0;i<n;i++)
After Edit : My Final Answer is
for(int i =(n - 1); i > 1; i--)
{
factorial = factorial * i;
}
for (int j=n-2;j<factorial;j++)
{
}

The simplest answer is
for (int i = 0; i < Factorial(n); i++) {...
In practice, usually O(n!) algorithms are those that work by trying all the different permutations of a list, that is, all the different ways you can reorder a list. One example is finding the shortest line that passes through all points in a map called the travelling salesman problem. You need to try all the different ways to go through all the points and that would be O(n!).
IEnumerable<List<int>> nextPermutation(List<int> nodesLeft)
{
if (nodesLeft.Count == 0)
{
yield return new List<int>();
}
else
{
for (int i = 0; i < nodesLeft.Count; i++)
{
List<int> newNodesLeft = new List<int>(nodesLeft);
newNodesLeft.removeAt(i);
foreach (List<int> subPermutation in nextPermutation(newNodesLeft)
{
subPermutation.add(nodesLeft[i]);
yield return subPermutation;
}
}
}
}
void main()
{
foreach (List<int> permutation in nextPermutation(new List<int>(new int[]{1,2,3,4,5}))) {
//every permutation of [1,2,3,4,5] will be generated here
//this will take O(n!) to complete, where n is the number of nodes given (5 in this case)
}
}

If recursion is allowed then:
void loop(int n)
{
if(n == 1)
return; // the program gets here exactly n! times
for(int i=0; i<n; i++)
loop(n-1);
}

If we're on the same page here... I think that would look like..
Tau(fetch) + Tau(store) + (2Tau(fetch) + Tau(<) )*(N + 1) + (2Tau(fetch) + Tau(+) + Tau(store)) * N

fact = 1;
for( c = 1 ; c <= n ; c++ )
{
fact = fact*c;
}
like this?

Related

Is there a way to do the sum of the n integers function that would have O(n^2)?

I want to write this simple function in a way that makes the big O notation of it O(n^2), how can I make that possible ?
int getSum(int n){
int sum = (n*(n+1))/2;
return sum;
any ideas?
I'm not really sure why you want this, but you could do it with two nested loops:
int getSum(int n) {
int sum = 0;
for(int i = 1; i <= n; i++) {
int x = 0;
while(x++ < i) {
sum++;
}
}
return sum;
}
This runs 1+2+3+...+n times, which simplifies to (n^2+n)/2, hence O(n^2)

I think I've found a good sorting algorithm. Seems to be faster than quickSort?

This works without comparing.
First, it finds the largest number in the array and saves it in a variable called "max". Then it creates a temporary array with the length of max + 1. After that, each "tempArray[i]" counts how often a number equal to "i" has been counted in the input array. In the end, it converts "tempArray" and writes it into the input array. See for yourself.
static int[] nSort(int[] array) {
int max = array[0];
for(int i = 1; i < array.length; i++) {
max = Math.max(max, array[i]);
}
Integer[] tempArray = new Integer[max+1];
for(int i = 0; i < array.length; i++) {
if(tempArray[array[i]] == null) {
tempArray[array[i]] = 0;
}
tempArray[array[i]]++;
}
for(int[] i = new int[2]; i[0] < max + 1; i[0]++) {
if(tempArray[i[0]] != null) {
while(tempArray[i[0]] > 0) {
array[i[1]] = i[0];
i[1]++;
tempArray[i[0]]--;
}
}
}
return array;
}
I've charted the measured runtime in a graph below. Green being my algorithm red and red being quicksort.
I've used this quicksort GitHub implementation and measured runtime in the same way as implemented there.
Runtime graph:

Am I crazy for thinking this program is O(n) runtime? My TA says it's O(n^2)

Code below, it should be O(n). There are two loops, I know this. But that doesn't necessarily mean it's O(n^2). The function loops won't run more than n + 1 times (at least as far as I can tell!). That should be O(n). Am I wrong? Can someone help me out? Thanks!
EDIT: The program puts odd integers at the front and even integers at the back of an array!!!
public class Main {
public static void main(String[] args) {
int[] array = new int[]{5, 4, 3, 2, 1, 0};
organizeArray(array);
for (int j = 0; j < array.length; j++) {
System.out.println(array[j]);
}
}
public static void organizeArray(int[] array) {
int end = array.length - 1;
for (int i = 0; i < array.length; i++) {
int temp = 0;
while (true) {
if (i == end)
break;
if (array[i] % 2 == 0) {
temp = array[i];
array[i] = array[end];
array[end] = temp;
end = end - 1;
}
if (array[i] % 2 != 0)
break;
}
if (i == end)
break;
}
}
}
As the other question was a duplicate of this one, let me post my answer here.
The code is O(n) as you either increase i or reduce end. In any case, you decrease the rest of work (n) by one.
For your upcoming homework: You can test your thoughts about big-O easily just by trying out. Most of the time the number of tests doesn't need to be very big. It will not be a proof but it gives you a good hint if your thoughts are correct or not.
Here's is my code for your problem with 100 tests. It produces 100 pairs of numbers: The length of the array and the number of loops. You take this list and bring it to a graph.
public class Main {
public static void main(String[] args) {
Main main = new Main();
Random random = new Random();
for (int i = 0; i < 100; i++) {
int[] array = new int[random.nextInt(10000 - 10) + 10]; // between 10 and 9999 numbers long
for (int j = 0; j < array.length; j++) array[j] = random.nextInt();
main.organize(array);
}
}
private int[] organize(int[] array) {
long loops = 0;
int end = array.length-1;
// I've shorten your code here. This does the same with less breaks
for (int i = 0; i < end; i++) {
while(i < end && array[i] % 2 == 0) {
swap(array, i, end--);
loops++;
}
}
System.out.printf("%d\t%d\n", array.length, loops);
return array;
}
private void swap(int[] array, int a, int b) {
int t = array[a];
array[a] = array[b];
array[b] = t;
}
}
And the graph looks like a straight line. So your proof should result in O(n), right?
Interesting code. The inner for loop will break when the i'th element is odd. If its not odd then it will swap elements from the end until an odd one is found. Since end is decremented upon each swap and the program completes when i reaches end, it follows that i or end can get incremented/decremented, respectively at most O(n) times. Because of this, and because all other operations in the loops are O(1), the program indeed runs in time O(n) despite there being nested loops.

Finding sum of fibonacci numbers recursively

I'm a bit stuck here. I know a particular fibonacci number can be found recursively as so:
int fib (int n)
{
if (n <= 1)
return n;
else
return fib(n-1) + fib(n-2);
}
And I know iteratively I could call that function n times to find the sum of fibonacci numbers
int sum = 0;
for (int i = 0; i < n; i++)
{
sum += fib(i);
}
But I'm having a hard time coming up with a recursive function to find the sum. I don't think it would be much different than the original fibonacci function. (This is for an assignment aimed at improving my ability to write ocaml syntax, not writing recursive functions)
Since no one else is bothering to answer your question, here you go:
int fib_sum(int n)
{
if (n == 0)
return 0;
if (n == 1)
return 1;
return fib_sum(n-1) + fib_sum(n-2) + 1;
}
If you want a recursive solution involving only fib_sum(), here is one:
int fib_sum (int n)
{
if (n == 0)
return 1;
if (n == 1)
return 2;
return fib_sum(n-1) + fib_sum(n - 2) + 1;
}
Observing that fib_sum(n) == fib(n+2) - 1 you can use more or less the same function.
I guess this will work fine
int fib_sum (int n){
if(n<=1) {
return n;
}
else {
return fib_Sum(n-1) + fib_Sum(n-2) + 1;
}
}
Keep in mind that counting of elements starts from 0
so elements 0 1 1 2 3 5 8 13
then position 0 1 2 3 4 5 6 7
So if n = 5, the sum = (0+1+1+2+3+5)=12
recursive function will be:
int fib_sum (int n){ if(n<=1) { return n; } else { return fib_Sum(n-1) + fib_Sum(n-2) + 1; } }

K-Server Dynamic Algorithm

I’m trying to get optimal solution for K-server problem for 3 servers using dynamic algorithm.
The idea is to generate all possible permutation and check them all to find the optimum value.
I understand it’s a slow exhaust search algorithm with exponential time big O.
Anyway, this is what I have, as far as I understand it should work, but it gives me false value.
here first 3 points are the servers. And dist(x,y) function calculate Cartesian distance of the points x-th and y-th.
void optimalSol()
{
int cost[10][10][10][10];
for(int l=3; l<=totalPoints; l++)
{
for(int i=0; i<=l; i++)
{
for(int j=0; j<=l; j++)
{
for(int k=0; k<=l; k++)
{
int current_min=99999;
//cost[i][j][k][l]=0;
if((i!=l) && (j!=l) && (k!=l))
cost[i][j][k][l]=99999;
else
{
for(int m=0; m<=l; m++)
{
if(current_min > (cost[m][j][k][l-1] + dist(m, i)))
{
if(cost[m][j][k][l-1] + dist(m, i)>0)
current_min = cost[m][j][k][l-1] + dist(m, i);
}
else if(current_min > (cost[i][m][k][l-1] + dist(m,j)))
{
if(cost[i][m][k][l-1] + dist(m,j)>0)
current_min = cost[i][m][k][l-1] + dist(m,j);
}
else if(current_min > (cost[i][j][m][l-1] + dist(m,k)))
{
if(cost[i][j][m][l-1] + dist(m,k)>0)
current_min = cost[i][j][m][l-1] + dist(m,k);
}
}
cost[i][j][k][l] = current_min;
}
}
}
}
}
printCostTable(cost);
}

Resources