The following java code finds the biggest common factor(GCD) for two numbers easily. Otherwise we need to check it from smallest number.Lets assume that the smallest number is n. So we need to check it from n,n-1....1 to find the common factor.But here out of two inputs set the biggest one to b. Then find the common factor using the % operator and keep changing the values of a and b until you find the common factor.
Code : (in JAVA)
Sample input and output
1.Input
8 5
Output
1
2.Input
26 4
Output
2
Please let me know if you have any questions .
Tuesday, July 10, 2012
Tuesday, July 12, 2011
Simple C Program to reverse Singly LinkedList using recursion
Code:
void reverse(struct node** headRef)
{
struct node* first;
struct node* rest;
if (*headRef == NULL)
return;
first = *headRef;
rest = first->next;
if (rest == NULL) return;
reverse(&rest);
first->next->next = first;
first->next = NULL;
*headRef = rest;
}
struct node* first;
struct node* rest;
if (*headRef == NULL)
first = *headRef;
rest = first->next;
if (rest == NULL) return;
reverse(&rest);
first->next->next = first;
first->next = NULL;
*headRef = rest;
}
Monday, June 28, 2010
Simple C Code to Create Magic matrix
First we have to understand what is magic matrix.
3 5 7 //rows,column,diagonal sum are equal
4 9 2 //here n is 3
Here is the code
void magic_matrix(int n) // N should be odd number...
{ int i,j,k,num=1;
i=1;
j=(1+n)/2;
for(k=0;k < n*n;k++)
{ a[i-1][j-1]=num;num++;
i--;
j++;
if(i==0) i=n;
if(j==n+1) j=1;
if(a[i-1][j-1]!=0)
{ i+=2;
j--;
if(i>n) i=i-n;
if(j==0) j=n;
}
}
for(i=0;i < n;i++)
{for(j=0;j < n;j++)
{ printf("%d\t",a[i][j]);
}
printf("\n");
}
}
- In magic matrix every rows and column sums are equal.
- Diagonal sum is also equal.
- The following code has O(n^2) time complexity.
- The example for magic matrix is given below.
3 5 7 //rows,column,diagonal sum are equal
4 9 2 //here n is 3
Here is the code
void magic_matrix(int n) // N should be odd number...
{ int i,j,k,num=1;
i=1;
j=(1+n)/2;
for(k=0;k
{ a[i-1][j-1]=num;num++;
i--;
j++;
if(i==0) i=n;
if(j==n+1) j=1;
if(a[i-1][j-1]!=0)
{ i+=2;
j--;
if(i>n) i=i-n;
if(j==0) j=n;
}
}
for(i=0;i < n;i++)
{for(j=0;j < n;j++)
{ printf("%d\t",a[i][j]);
}
printf("\n");
}
}
Subscribe to:
Posts (Atom)