Showing posts with label My Codes. Show all posts
Showing posts with label My Codes. Show all posts

Thursday, February 28, 2013

Find Greatest Common Devicer Using Java

 import java.util.*;  
 public class GCD{  
      public static void main(String args[]){  
           int integer1,integer2,GCD;  
           Scanner scanner = new Scanner(System.in);  
           try{  
                System.out.print("\n\n\nEnter Two Integers(separate by space) : ");  
                integer1 = scanner.nextInt();  
                integer2 = scanner.nextInt();  
                if(integer1==0||integer2==0){  
                     System.out.println("Error:Can not find GCD for 0");  
                     System.exit(-1);  
                }  
                GCD=GCD(integer1,integer2);  
                System.out.println("GCD of "+integer1+" and "+integer2+" is "+GCD);  
           }catch(Exception e){  
                System.out.println("Error:Integer values must be given");  
           }  
      }  
      private static int GCD(int integer1,int integer2){  
           int temp=0;  
           if(integer1>integer2){  
                while(integer1>0){  
                     temp=integer2 % integer1;  
                     integer2=integer1;  
                     integer1=temp;  
                }  
                return integer2;  
           }  
           else if(integer1<integer2){  
                while(integer2>0){  
                     temp=integer1 % integer2;  
                     integer1=integer2;  
                     integer2=temp;  
                }  
                return integer1;  
           }  
           else{  
                return integer1;  
           }  
      }  
 }  

Find Prime Factors Of Given Integer Using Java

 import java.util.*;  
 public class primeFactor{  
      public static void main(String args[]){  
           int integer;  
           Scanner scanner = new Scanner(System.in);  
           List<Integer> factors = new ArrayList<Integer>();  
           try{  
                System.out.print("\n\n\nEnter Integer : ");  
                integer = scanner.nextInt();  
                if(integer==0){  
                     System.out.println("Error:Can not find primes for 0");  
                     System.exit(-1);  
                }  
                System.out.print(integer+" = ");  
                for (Integer integer1 : FindSmallestFactors(integer)) {  
                     System.out.print(integer1+" ");  
                }  
           }catch(Exception e){  
                System.out.println("Error:Integer values must be given");  
           }  
      }  
      private static List<Integer> FindSmallestFactors(int integer){  
           List<Integer> factors = new ArrayList<Integer>();  
           for (int i = 2; i <= integer; i++) {  
                while (integer % i == 0) {  
                     factors.add(i);  
                     integer = integer / i;  
                }  
           }  
           return factors;  
      }  
 }  

Find Prime Numbers Using Java

 import java.util.*;  
 public class Primes{  
      public static void main(String args[]){  
           int integer;  
           Scanner scanner = new Scanner(System.in);  
           List<Integer> factors = new ArrayList<Integer>();  
           try{  
                System.out.print("\n\n\nEnter Integer : ");  
                integer = scanner.nextInt();  
                if(integer==0){  
                     System.out.println("Error:Can not find primes for 0");  
                     System.exit(-1);  
                }  
                 for (Integer integer1 : Primes(integer)) {  
                     System.out.print(integer1+"\t");  
                }  
           }catch(Exception e){  
                System.out.println("Error:Integer values must be given");  
           }  
      }  
      private static List<Integer> Primes(int integer){  
           List<Integer> factors = new ArrayList<Integer>();  
           for (int i = 1; i <= integer; i++) {  
                for(int j=2;j<=i;j++){  
                     if(i==j){  
                          factors.add(i);  
                          break;  
                     }  
                     //value is not prime  
                     if(i %j==0){  
                          break;  
                     }  
                }  
           }  
           return factors;  
      }  
 }  

Using Sieve of Eratosthenes

 About Sieve of Eratosthenes. This method is more faster than above prime number finding method.
 import java.util.*;  
 //create a structure  
 class list{  
      int value;  
      char flag;  
 }  
 public class ex{  
      public static void main(String args[]){  
           int integer;  
           Scanner scanner = new Scanner(System.in);  
           try{  
                System.out.print("\n\n\nEnter Integer : ");  
                //get integer  
                integer = scanner.nextInt();  
                if(integer==0){  
                     System.out.println("Error:Can not find primes for 0");  
                     System.exit(-1);  
                }  
                PrimesSieveOfEratosthenes(integer);  
           }catch(Exception e){  
                System.out.println("Error:Integer values must be given");  
           }  
      }  
      private static void PrimesSieveOfEratosthenes(int integer){  
           list integers[]=new list[integer];  
           //initialize list elements  
           for(int m=0;m<integers.length;m++){  
                integers[m]=new list();  
           }  
           //add values to list elements  
           for(int i=1;i<integer;i++){  
                integers[i].value=i+1;  
                integers[i].flag='0';  
           }  
           //find prime numbers  
           for(int k=2;k<=integer;k++){  
                if(integers[k-1].flag=='0'){  
                     for(int j=2*k-1;j<integer;j=j+k){  
                          integers[j].flag='1';  
                     }  
                }  
           }  
           //print prime numbers  
           for(int l=1;l<integer;l++){  
                if(integers[l].flag=='0'){  
                     System.out.print(integers[l].value+"\t");  
                }  
           }  
      }  
 }  

Wednesday, February 27, 2013

File Encryption and Decryption using AES Symmetric key Cryptographic algorithm

In this work, i encrypt a web page by running EncryptFile.java, then host that encrypted file to the server. Then another client can download that file from the server and decrypt it by running DecryptFile.java if that client has secret key.

EncrypFile.java

 import java.security.*;  
 import java.io.*;  
 import javax.crypto.*;  
 import javax.crypto.spec.*;  
 public class EncryptFile {  
      public static void main(String args[]) {  
           if (args.length < 1) {  
                System.out.println("Usage: java EncryptFile <file name>");  
                System.exit(-1);  
           }  
           try {  
                File aesFile = new File("Encrypted Web Page.html");  
                FileInputStream fis;  
                FileOutputStream fos;  
                CipherInputStream cis;  
                 //Creation of Secret key  
                String key = "MySEcRetKeY";  
                int length=key.length();  
                if(length>16 && length!=16){  
                     key=key.substring(0, 15);  
                }  
                if(length<16 && length!=16){  
                     for(int i=0;i<16-length;i++){  
                          key=key+"0";  
                     }  
                }  
                SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(),"AES");  
                 //Creation of Cipher objects  
                Cipher encrypt =Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");  
                encrypt.init(Cipher.ENCRYPT_MODE, secretKey);  
                // Open the Plaintext file  
                try {  
                     fis = new FileInputStream(args[0]);  
                     cis = new CipherInputStream(fis,encrypt);  
                     // Write to the Encrypted file  
                     fos = new FileOutputStream(aesFile);  
                     byte[] b = new byte[8];  
                     int i = cis.read(b);  
                     while (i != -1) {  
                          fos.write(b, 0, i);  
                          i = cis.read(b);  
                     }  
                     fos.flush();  
                     fos.close();  
                     cis.close();  
                     fis.close();  
                } catch(IOException err) {  
                     System.out.println("Cannot open file!");  
                     System.exit(-1);  
                }  
           } catch(Exception e){  
                e.printStackTrace();  
           }  
      }  
 }  

DecryptFile.java

 import java.security.*;  
 import java.io.*;  
 import javax.crypto.*;  
 import javax.crypto.spec.*;  
 import java.net.*;  
 public class DecryptFile {  
      public static void main(String args[]) {  
           try {  
                File aesFile = new File("Downloaded Encrypted Web Page.html");  
                // if file doesnt exists, then create it  
                if (!aesFile.exists()) {  
                     aesFile.createNewFile();  
                }  
                aesFile=retrieve(args);  
                File aesFileBis = new File("Decrypted Web Page.html");  
                FileInputStream fis;  
                FileOutputStream fos;  
                CipherInputStream cis;  
                 //Creation of Secret key  
                String key = "MySEcRetKeY";  
                int length=key.length();  
                if(length>16 && length!=16){  
                     key=key.substring(0, 15);  
                }  
                if(length<16 && length!=16){  
                     for(int i=0;i<16-length;i++){  
                          key=key+"0";  
                     }  
                }  
                SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(),"AES");  
                 //Creation of Cipher objects  
                Cipher decrypt =Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");  
                decrypt.init(Cipher.DECRYPT_MODE, secretKey);  
                // Open the Encrypted file  
                fis = new FileInputStream(aesFile);  
                cis = new CipherInputStream(fis, decrypt);  
                // Write to the Decrypted file  
                fos = new FileOutputStream(aesFileBis);  
                byte[] b = new byte[8];  
                int i = cis.read(b);  
                while (i != -1) {  
                     fos.write(b, 0, i);  
                     i = cis.read(b);  
                }  
                fos.flush();  
                fos.close();  
                cis.close();  
                fis.close();  
           } catch(Exception e){  
                e.printStackTrace();  
           }  
      }  
      public static File retrieve(String args[]){  
           if (args.length!=1) {  
                System.out.println("Usage: UrlRetriever <URL>");  
                System.exit(-1);  
           }  
           File file = new File("Downloaded Encrypted Web Page.html");  
           try {  
                URL url=new URL(args[0]);  
                BufferedInputStream buffer=new  
                BufferedInputStream(url.openStream());  
                DataInputStream in= new DataInputStream(buffer);  
                String line;  
                // if file doesnt exists, then create it  
                if (!file.exists()) {  
                     file.createNewFile();  
                }  
                FileWriter fw = new FileWriter(file);  
                BufferedWriter bw = new BufferedWriter(fw);  
                while ((line=in.readLine())!=null){  
                     bw.write(line);  
                }  
                bw.close();  
                in.close();  
           } catch(MalformedURLException mue) {  
                System.out.println(args[0]+"is an invalid URL:"+mue);  
           }catch(IOException ioe) {  
                     System.out.println("IOException: "+ioe);  
           }  
           return file;  
      }  
 }  

You can download my work out HERE

Saturday, November 24, 2012

Very Simple My Own Shell in C

Do you want to publish source codes in your blog or web site as follows.
Visit Source Code Formatter
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<string.h>  
 int main(){  
       char buf[256]={0};  
       printf("\n\n\n");  
       while(1){  
            printf("\nMOSH : ");  
            if (fgets(buf, sizeof(buf), stdin) == NULL){  
                fprintf(stderr, "Invalid input command!\n");  
                exit(-1);  
              }  
              buf[strlen(buf)-1]='\0';  
            system(buf);  
       }       
       return 0;  
 }  

Saturday, November 10, 2012

Maximum matching in bipartite graph using Hopcroft Karp algorithm in C ++

Do you want to publish source codes in your blog or web site as follows.
Visit Source Code Formatter
 /*******************************************************/  
 /*       2nd Takehome Assignment         */  
 /*Instructions :                    */  
 /*   Data should be input to the program using text */  
 /*     file (EX: test.txt)            */  
 /*   INPUT FORMAT:                 */  
 /*     4 5 5                   */  
 /*     1 8                    */  
 /*     1 5                    */  
 /*     2 6                    */  
 /*     3 9                    */  
 /*     4 7                    */  
 /*   first three integers (n,m and e)        */  
 /*     n: number of left hand nodes        */  
 /*     m: number of right hand node        */  
 /*     e: number of incedent edges        */  
 /*    next integer(g[u][v])            */  
 /*      g[u][v]: adjecent verteces        */  
 /*******************************************************/  
 #include <iostream>  
 #include <vector>  
 #include <stdio.h>  
 #include <stdlib.h>  
 #include <string.h>  
 #include <queue>  
 #include <fstream>  
 using namespace std;  
 #define MAX 10000 //maximum allowed couples  
 #define NIL 0  
 #define INF (1<<28) //infinity  
 vector<int> G[MAX]; // G[0]= NIL u G1[G[1---n]] u G2[G[n+1---n+m]]  
 int n,m,e,match[MAX],dist[MAX];  
 //Breadth first search  
 bool bfs() {  
   int i, u, v, len;  
   queue<int> Q;  //an integer queue  
   for(i=1; i<=n; i++) {  
     if(match[i]==NIL) { //i is not matched  
       dist[i] = 0;  
       Q.push(i);  
     }  
     else dist[i] = INF;  
   }  
   dist[NIL] = INF;  
   while(!Q.empty()) {  
     u = Q.front();  
     Q.pop();  
     if(u!=NIL) {  
       len = G[u].size();  
       for(i=0; i<len; i++) {  
         v = G[u][i];  
         if(dist[match[v]]==INF) {  
           dist[match[v]] = dist[u] + 1;  
           Q.push(match[v]);  
         }  
       }  
     }  
   }  
   return (dist[NIL]!=INF);  
 }  
 //depth first search  
 bool dfs(int u) {  
   int i, v, len;  
   if(u!=NIL) {  
     len = G[u].size();  
     for(i=0; i<len; i++) {  
       v = G[u][i];  
       if(dist[match[v]]==dist[u]+1) {  
         if(dfs(match[v])) {  
           match[v] = u;  
           match[u] = v;  
           return true;  
         }  
       }  
     }  
     dist[u] = INF;  
     return false;  
   }  
   return true;  
 }  
 int hopcroft_karp() {  
   int matching = 0, i;  
   // match[] is assumed NIL for all vertex in G  
   while(bfs())  
     for(i=1; i<=n; i++)  
       if(match[i]==NIL && dfs(i))  
         matching++;  
   return matching;  
 }  
 //read data file in to an array  
 int openDataFile(char *filename){  
   int A, B;  
   ifstream infile(filename);  
   if (!infile) { //fill not found  
     printf("There was a problem opening file %s for reading.\n",filename);  
     return 0;  
   }  
   printf("Opened %s for reading.\n", filename); //file opened  
   infile >> n >> m >>e; // for perfect matching n=m  
   while (infile >> A >> B) { //read adjecent verteces  
     G[A].push_back(B);  
   }  
 }  
 //main method starts here  
 int main() {  
   printf("\n*******************************\n\tFind Stable Cuples\n*******************************\n");  
   char filename[256] = {0};  
   int NumOfMatches,i;  
   printf("Enter data file name : ");  
   scanf("%s",&filename);  
   openDataFile(filename);  
   while(1){  
     int choice;  
     printf("\n*******************************\n\tFind Stable Cuples\n*******************************\n");  
     printf("Enter 1 : Find Optimal Solution\n");  
     printf("Enter 2 : Add New Data File\n");  
     printf("Enter 0 : Exit\n");  
     printf("\nEnter :");  
     scanf("%d",&choice);  
     if(choice==1){  
       openDataFile(filename);  
       NumOfMatches=hopcroft_karp(); //find matching perfect matching couples  
       printf("Number of couples matched : %d\n",NumOfMatches);  
       for(i=1;i<=n;i++){  
         printf("%d matched with %d\n",i,match[i]);  
       }  
     }else if(choice==2){  
       printf("Enter data file name : ");  
       scanf("%s",&filename);  
     }  
     else if(choice==0){  
       printf("Program Terminated\n");  
       exit(0);  
     }  
     else{  
       printf("Error : Wrong Input\n");  
     }  
   }  
   return 0;  
 }  

Maximum matching in bipartite graph using Ford Fulkerson algorithm in C

Do you want to publish source codes in your blog or web site as follows.
Visit Source Code Formatter
 /*******************************************************/  
 /*       2nd Takehome Assignment         */  
 /*    Maximum matching marriage couples using   */  
 /*      Ford Fulkerson Algorithm         */  
 /*Instructions :                    */  
 /*   Data should be input to the program using text */  
 /*     file (EX: test.txt)            */  
 /*   INPUT FORMAT:                 */  
 /*     10 10                   */  
 /*     1 6                    */  
 /*     1 7                    */  
 /*     2 7                    */  
 /*     3 6                    */  
 /*     3 8                    */  
 /*     3 10                    */  
 /*     4 7                    */  
 /*     4 10                    */  
 /*     5 7                    */  
 /*     5 9                    */  
 /*   first two integers (n and e)          */  
 /*     n: number of nodes in the graph      */  
 /*     e: number of incedent edges        */  
 /*    next integer(u,v)              */  
 /*      g[u][v]: adjecent verteces        */  
 /*******************************************************/  
 #include <stdio.h>  
 #include <stdlib.h>  
 // Basic Definitions  
 #define WHITE 0   //nodes status  
 #define GRAY 1  
 #define BLACK 2  
 #define MAX_NODES 1000   //maximum allowed nodes  
 #define INFINITY 1000000000  
 // variable Declarations  
 int n; // number of nodes  
 int e; // number of edges  
 int capacity[MAX_NODES][MAX_NODES]; // capacity matrix  
 int flow[MAX_NODES][MAX_NODES];   // flow matrix  
 int color[MAX_NODES]; // store node status  
 int parent[MAX_NODES]; // array to store augmenting path  
 int min (int x, int y) {  
   return x<y ? x : y; // returns minimum of x and y  
 }  
 // A Queue for Breadth-First Search  
 int head,tail;  
 int q[MAX_NODES+2];  
 void enqueue (int x) { //add to queue  
   q[tail] = x;  
   tail++;  
   color[x] = GRAY;  
 }  
 int dequeue () {    //remove from queue  
   int x = q[head];  
   head++;  
   color[x] = BLACK;  
   return x;  
 }  
 // Breadth-First Search for an augmenting path  
 int bfs (int start, int target) {  
   int u,v;  
   for (u=0; u<n+2; u++) { //initialize node status  
     color[u] = WHITE;  
   }  
   head = tail = 0;  
   enqueue(start);  
   parent[start] = -1;  
   while (head!=tail) {  
     u = dequeue();  
     // Search all adjacent white nodes v. If the capacity  
     // from u to v in the residual network is positive,  
     // enqueue v.  
     for (v=0; v<n+2; v++) {  
       if (color[v]==WHITE && capacity[u][v]-flow[u][v]>0) {  
         enqueue(v);  
         parent[v] = u;  
       }  
     }  
   }  
   // If the color of the target node is black now,  
   // it means that we reached it.  
   //printf("%d\n",color[target]);  
   return color[target]==BLACK;  
 }  
 // Ford-Fulkerson Algorithm  
 int max_flow (int source, int sink) {  
   int i,j,u;  
   // Initialize empty flow.  
   int max_flow = 0;  
   for (i=0; i<n+2; i++) {  
     for (j=0; j<n+2; j++) {  
       flow[i][j] = 0;  
     }  
   }  
   // While there exists an augmenting path,  
   // increment the flow along this path.  
   printf("\nAugmented Path :\n");  
   while (bfs(source,sink)) {  
     // Determine the amount by which we can increment the flow.  
     int increment = INFINITY;  
     for (u=sink; parent[u]!=(-1); u=parent[u]) {  
       increment = min(increment,capacity[parent[u]][u]-flow[parent[u]][u]);  
     }  
     //printf("\n%d\n",increment);  
     // Now increment the flow.  
     for (u=sink; parent[u]!=(-1); u=parent[u]) {  
       flow[parent[u]][u] += increment;  
       flow[u][parent[u]] -= increment; // Reverse in residual  
     }  
     printf("\t");  
     // Path trace  
     for (u=sink; parent[u]!=(-1); u=parent[u]) {  
       printf("%d<-",u);  
     }  
     printf("%d adds %d incremental flow\n",source,increment);  
     max_flow += increment;  
     //printf("\n\n%d %d\n\n",source,sink);  
   }  
   //printf("%d\n",s);  
   // No augmenting path anymore. We are done.  
   return max_flow;  
 }  
 // Reading the input file and the main program  
 int read_input_file() {  
   int a,b,i,j;  
   char filename[256] = {0};  
   printf("Enter data file name : ");  
   scanf("%s",&filename);  
   FILE* input = fopen(filename,"r");  
   if(!input){  
     printf("There was a problem opening file %s for reading.\n",filename);  
     return 0;  
   }  
   // read number of nodes and edges  
   fscanf(input,"%d %d",&n,&e);  
   // initialize empty capacity matrix  
   for (i=0; i<n+2; i++) {  
     for (j=0; j<n+2; j++) {  
       capacity[i][j] = 0;  
     }  
   }  
   // read edge capacities  
   for (i=0; i<e; i++) {  
     fscanf(input,"%d %d",&a,&b);  
     if(a==b){  
       printf("ERROR : Graph is not bipartite");  
       return 0;  
     }  
     capacity[a][b]= 1; // Could have parallel edges  
   }  
   fclose(input);  
   for(i=0;i<n/2;i++){  
     capacity[0][i+1]= 1;  
     capacity[i+6][n+1]= 1;  
   }  
   return 1;  
 }  
 //Extra works  
 /*void read_input_file_w() {  
   int a,b,c,i,j;  
   FILE* input = fopen(filename,"a+");  
   // read number of nodes and edges  
   fscanf(input,"%d %d",&n,&e);  
   // initialize empty capacity matrix  
   for (i=0; i<n+2; i++) {  
     for (j=0; j<n+2; j++) {  
       capacity[i][j] = 0;  
     }  
   }  
   // read edge capacities  
   for (i=0; i<e; i++) {  
     fscanf(input,"%d %d",&a,&b);  
     capacity[b][a]= 1; // Could have parallel edges  
   }  
   fclose(input);  
   for(i=0;i<n/2;i++){  
     capacity[0][i+6]= 1;  
     capacity[i+1][n+1]= 1;  
   }  
 }  
 void printMatrix(){  
   int i,j;  
   for (i=0; i<=n+1; i++) {  
     for (j=0; j<=n+1; j++) {  
       printf("%d ",capacity[i][j]);  
     }  
     printf("\n");  
   }  
 }*/  
 int start(){  
   int isBipartite=0;  
   while(!isBipartite){  
     printf("\n*******************************\n\tFind Stable Cuples\n*******************************\n");  
     isBipartite=read_input_file();  
     //printMatrix();  
   }  
   return isBipartite;  
 }  
 int main () {  
   int i,j;  
   int isBipartite=0;  
   isBipartite=start();  
   while(isBipartite){  
     int choice;  
     printf("\n*******************************\n\tFind Stable Cuples\n*******************************\n");  
     printf("Enter 1 : Find Optimal Solution\n");  
     printf("Enter 2 : Add New Data File\n");  
     printf("Enter 0 : Exit\n");  
     printf("\nEnter :");  
     scanf("%d",&choice);  
     if(choice==1){  
       printf("\ntotal flow is %d\n",max_flow(0,n+1));  
       printf("\nMatched couples:\n");  
       for (i=1; i<=n; i++)  
           //printf("%d ",parent[i]);  
         for (j=1; j<=n; j++)  
           if (flow[i][j]>0)  
             printf("\tMen:%d matched with Women:%d\n",i,j);  
     }else if(choice==2){  
       isBipartite=start();  
       //printMatrix();  
     }  
     else if(choice==0){  
       printf("Program Terminated\n");  
       exit(0);  
     }  
     else{  
       printf("Error : Wrong Input\n");  
     }  
   }  
   return 0;  
 }  

Wednesday, September 19, 2012

Simple Hello World Game In C

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter
 ////////////////////////////A Hello World for game/////////////////////////////////  
 ///////////////////////////////By croosetech///////////////////////////////////////  
 /////////////////Visit croosetech.blogspot.com for more////////////////////////////  
 #include <stdio.h>  
 #include <stdlib.h>  
 #include <string.h>  
 #include <time.h>  
 int main(){  
        int a=0,i=0,answer=0,last=0,x=0,exit=0;  
        last=10;  
        unsigned int iseed = (unsigned int)time(NULL);  
     srand (iseed);  
        while(x<5){  
             i=3;  
             a=rand()%last;   
             printf("\n****************************************\n");  
           printf("\tThis is a Hello World Game\n");  
           printf("****************************************\n");  
             printf("I have a number between 0 to %d.\n\n",last-1);  
             while(i>0){  
                  printf("Try to guess my number(%i attemps remaining): ",i);   
                  scanf("%d", &answer);  
                  if(answer<a){  
                       printf("\nYours %d is too small...\n", answer);   
                       i--;  
                       continue;  
                  }  
                  if(answer>a){  
                       printf("\nYours %d is too big...\n", answer);   
                       i--;  
                       continue;  
                  }  
                  if(answer==a){  
                       printf("\nYou're Right! My number is %d!\n\n\t\tCongratz...", a);   
                       break;  
                  }  
             }  
             if(i==0){  
                  printf("\n\t\tYou are looser !!!.\n\t\t GAME OVER\n");  
                  printf("****************************************\n");  
                  printf("To try again press 1(any other to exit): ");  
                  scanf("%d", &exit);  
                  if(exit==1){  
                       x=0;  
                       last=10;  
                       continue;  
                  }  
                  else {  
                       printf("Good bye!!!");  
                       return 0;  
                  }  
             }  
             else{  
                  printf("Now you are move on to next level\n\n");  
                  x++;  
                  last=last+10;  
                  continue;  
             }  
       }  
       if(x==5){  
            system("clear");  
            printf("\t\tAWESOME PERFORMANCE\n\n\n");  
       }  
      return 0;    
 }  

Tuesday, August 14, 2012

Numerical Integration using simpson rules and recusion in fortran

 There is a simple integration using fortran. For the given function (x^n*e^(x-1)) to integrate we can use recursion. For other functions recursion may not support. So if you change the function make sure it will support integration and if it is make sure given integration formula is correct.
Compilation
           gfortran <filename>.f
it will create default executable. in windows a.exe and in linux a.out.
simply type 'a' to run in wndows and './a' to run in linux.
If you have any problem comment me.
--------------------------------------------------------------------------------------------------------------
         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter
    program integration  
 ! declaring the variable values  
    real results,simp13_res,simp38_res,a,b,error  
    real f  
    integer n  
    external f  
      results=0.0  
            n=0  
            a=0.0  
            b=1.0  
      error=0.0  
     write(*,*)achar(10),achar(10)  
     write(*,*)"Intergration of (x^n*e^(x-1)) by dx range of 0 to 1"   
 10   write(*,*)achar(10)  
     write(*,*)"Enter 0 to exit from the program"  
     write(*,*)"Enter n : "   
     read(*,'(i10)')n   
 !to exit            
     if(n==0)then  
            goto 20  
     end if  
 !factorial function calling  
     results=factorial(n)  !calling the function factorial  
     write(*,*)achar(10),"Recursion Solution = ",results  ! print the value of the function  
 !get simpson 1/3 solution  
     call simpson13(f,a,b,simp13_res,real(n))  
     write(*,*)achar(10),"Simpson 1/3 Solution= ",simp13_res  
                 error=(results-simp13_res)*100/results  
     write(*,*)"Relative True Error in Simpson 1/3 (%) = ",abs(error)  
                 error=0.0  
 !get simpson 3/8 solution                  
     call simpson38(f,a,b,simp38_res,real(n))  
     write(*,*)achar(10),"Simpson 3/8 Solution = ",simp38_res  
                 error=(results-simp38_res)*100/results  
     write(*,*)"Relative True Error in Simpson 3/8 (%) = ",abs(error)  
 !continue                  
    goto 10  
 20  continue  
    end program integration  
 ! end of the main program, functions are below which is used in this program  
 !recursive algorithm  
    recursive function factorial(n) result(results)  
            real results,first,x  
      integer n  
             x=1  
             first=1/exp(x)  
       if(n<=0) then  
        results = 0  
        return  
             else if(n==1) then  
                    results=1/exp(x)  
              return  
             else  
                    results=1-n*factorial(n-1)  
                    return  
             end if  
    end function factorial  
 !simpson 1/3 algorithm  
    Subroutine simpson13(f,a,b,simp38_res,n)  
            real a,b,x,n,h,f,simp38_res  
                  h=(b-a)/2.0  
      simp38_res=h*(f(a,n)+f(a+h,n)+f(b,n))/3.0  
      return  
    end Subroutine simpson13  
 !simpson 3/8 algorithm  
    Subroutine simpson38(f,a,b,simp13_res,n)  
            real a,b,x,n,h,f,simp13_res  
                  h=(b-a)/3.0  
      simp13_res=h*3.0*(f(a,n)+3.0*f(a+h,n)+3.0*f(a+2*h,n)+f(b,n))/8.0  
      return  
    end Subroutine simpson38  
 !function to integrate  
    function f(x,n) result(res)  
            real x,n,res  
            res=(x**n)*exp(x-1)  
      return  
    end function f  

Sunday, August 12, 2012

Very simple virus for windows in c

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 //simple virus for windows. for education purpose only  
 //this will create infinite number of directories  
 //in your execution directory  
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<dos.h>  
 #include <windows.h>  
   
 int main(){  
    for(;;){  
       system("mkdir %random%");  
    }  
    return 0;  
 }  

Wednesday, August 1, 2012

Simple Boot Loader From Assembly Language

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 [bits 16]  
 [org 0x7c00]  
   
 mov si,msg1  
 call printchar  
 mov si,act1  
 call printchar  
 mov si,msg2  
 call printchar  
   
 jmp $  
   
 printchar:  
   mov al,[si]  
   cmp al,0  
   je next  
   call print  
   inc si  
   call printchar  
   
 print:  
   mov ah,0x0E  
   mov bh,0x00  
   mov bl,0x07  
   int 0x10  
   ret  
 next:  
   ret  
   
 msg1 db "Boot loader starts...",0  
 act1 db "Boot loader executing.......",0  
 msg2 db "Boot loader exits....",0  
   
 times 510-($-$$) db 0  
 dw 0xAA55  

Friday, July 20, 2012

Thread Handling Example in C

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 #include <stdio.h>  
 #include <pthread.h>  
 #include <stdlib.h>  
 #include <signal.h>  
   
   
 #define ARRAYSIZE 1000  
 #define THREADS 10  
   
 void *slave(void *myid);  
   
   
 /* shared data */  
 int data[ARRAYSIZE]; /* Array of numbers to sum */  
 int sum = 0;  
 pthread_mutex_t mutex; /* mutually exclusive lock variable */  
 //int wsize;     /* size of work for each thread */   
 /* end of shared data */  
 FILE *file;  
 char filename[25];  
   
 pthread_t tid[THREADS];  
 int wsize = ARRAYSIZE/THREADS;   
 int k=1;  
   
 void pwrproc(int s)  
 {  
 k=0;  
   
 }  
   
   
   
 void *slave(void *myid)  
 {  
 int i,low,high,myresult=0;  
 printf("thread %u is created.\n",(unsigned int)pthread_self());  
 while(k) sleep(5);  
 printf("thread %u has recieved signal.\n",(unsigned int)pthread_self());  
 low=(int)myid*wsize;  
 high = low + wsize;  
   
   for (i=low;i<high;i++)  
       myresult += data[i];  
   
 fprintf(file,"The sum from %d to %d is %d \n",low,high,myresult);  
 pthread_mutex_lock(&mutex);  
 sum += myresult;  
 pthread_mutex_unlock(&mutex);  
   
 return myid;  
 }  
   
 main()  
 {  
   
   int i=0;  
   signal(SIGPWR,pwrproc);  
   
   fprintf(stdout, "Enter the File Name: ");  
   fscanf(stdin,"%s",filename);  
   file= fopen(filename,"w");  
   fprintf(file,"The process ID is %d\n",getpid());  
   fprintf(file,"The Parent Process ID is %d\n\n",getppid());  
   //fclose(file);  
   
   printf("The process ID is %d\n",getpid());  
   printf("The Parent Process ID is %d\n",getppid());  
   pthread_mutex_init(&mutex,NULL); /* initialize mutex */  
   
    /* wsize must be an integer */  
   
     for(i=0;i<ARRAYSIZE;i++)    /* initialize data[] */  
       data[i] = i+1;  
   
     
    for (i=0;i<THREADS;i++) /* create threads */  
       if (pthread_create(&tid[i],NULL,slave,(void *)i) != 0)  
          perror("Pthread_create fails");  
   
    for (i=0;i<THREADS;i++) /* join threads */  
       if (pthread_join(tid[i],NULL) != 0)  
          perror("Pthread_join fails");  
     
    printf("The sum from 1 to %i is %d\n",ARRAYSIZE,sum);  
   
   printf("The Signal is reached. Data is saved in - %s\n",filename);  
   
 }  

Hashing To Strore Intergers From File And Search In C

 This is hashing program. That stores 100000 integers from file called hashInt.txt to an array using hashing.
you can download hashInt.txt file from the following link
download
If you are in trouble in understanding this please comment me
-------------------------------------------------------------------------------------
         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 #include<stdio.h>  
 #include <stdlib.h>  
 #include <time.h>  
   
 #define ARR_SIZE 100000 //Number of integers in the file  
 #define TAB_SIZE 10000 //hash table size  
   
 int hash_func( int key);  
 int hash_search(int key,int value);  
   
 typedef struct hash_node{  
     
   int key;  
   struct hash_node *left;  
   struct hash_node *right;  
       
 }NODE;  
   
 int target_sum[]={231552,234756,596873,648219,726312,981237,988331,1277361,1283379};  
 NODE *hash_tab[TAB_SIZE];  
 int numbers[ARR_SIZE];  
   
 main(){  
   clock_t start = clock();  
   int i,k,key;  
   FILE *fr;  
   fr=fopen("HashInt.txt","r");  
   //intialize hash_tab array null  
   for (i=0;i<TAB_SIZE;i++){  
     hash_tab[i]=NULL;  
   }  
   i=0;  
   //get line by linee int  
   while(fscanf(fr,"%d",&key)!=EOF){  
     numbers[i]=key;  
     i++;  
     NODE *node=malloc(sizeof(NODE));  
     //get index of key  
     int index=hash_func(key);  
     //not collissions found  
     if(hash_tab[index]==NULL){  
       hash_tab[index]=node;  
       node->key=key;  
       node->right=NULL;  
       node->left=NULL;  
     }  
     //collission found  
     else{  
       NODE *p=hash_tab[index];  
       //binary search for an free node  
       while(p!=NULL){  
         if(p->key>key){  
           p=p->right;  
         }  
         else{  
           p=p->left;  
         }  
       }  
       p=node;  
       node->key=key;  
       node->right=NULL;  
       node->left=NULL;  
     }  
   }  
   fclose(fr);  
   //find target sums  
   for(k=0;k<9;k++){  
     int found=0;  
     for(i=0;i<ARR_SIZE;i++){  
       key=target_sum[k]-numbers[i];  
       if(key > 0){  
         if(hash_search(key,numbers[i])){  
           found=1;    
           printf("1");  
           break;  
         }  
       }  
     }  
     if(!found){  
       printf("0");  
     }  
   }  
   printf("\n");  
   printf("Time elapsed: %f\n", ((double)clock() - start) / CLOCKS_PER_SEC);      
 }  
   
 //hash function  
 int hash_func( int key){  
   return key/100;  
 }  
 //hash search function  
 int hash_search(int key,int value){  
   int index=hash_func(key);  
   //index exeeds the array size  
   if(index>=TAB_SIZE){  
     return 0;  
   }  
     
   NODE *p=hash_tab[index];  
   //find key  
   if(p!=NULL){  
     int twise=0;  
     while(p!=NULL){  
       if(key==value){  
         if(p->key>key){  
           p=p->right;  
         }  
         else if(p->key<key){  
           p=p->left;  
         }  
         else{  
           if(twise){  
             return 0;  
           }  
           p=p->left;  
           twise++;  
         }  
       }  
       else{  
         if(p->key>key){  
           p=p->right;  
         }  
         else if(p->key<key){  
           p=p->left;  
         }  
         else{  
           return 1;  
         }  
       }  
     }  
     return 0;      
   }  
   else{  
     return 0;  
   }  
 }  

Rabin Carp String Matchin Algorithm In C

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 #include <stdio.h>  
 #include <stdlib.h>  
 #include <string.h>  
 #include <errno.h>  
   
 int found_f=0,found_r=0,pat_val=0;  
   
 int main (){  
   system("clear");  
 while(1){  
   int i,j=0;  
   char pattern[256]={0};  
   char filename[256] = {0};  
   //Get file  
   printf("Enter path of file to read(q to exit): ");  
      if (fgets(filename, sizeof(filename), stdin) == NULL){  
        fprintf(stderr, "Invalid input!\n");  
        exit(-1);  
      }  
   
   filename[strlen(filename) - 1] = '\0';  
   FILE *file = fopen(filename, "r");  
   if(filename[0]=='q'){  
     system("clear");  
     printf("Program Exited!!!\n");  
     exit(0);  
   }  
     if (!file){  
        fprintf(stderr, "Unable to open %s: %s\n",  
        filename, strerror(errno));  
        continue;  
   }  
   //Get file size  
   fseek(file, 0L, SEEK_END);  
   int sz = ftell(file);  
   fseek(file, 0L, SEEK_SET);  
     
   //create file size array  
   char buffer[sz];  
   for(i=0;i<sz;i++){  
     buffer[i]=0;  
   }  
     
   //Get pattern  
   printf("Enter pattern to check : ");  
      if (fgets(pattern, sizeof(pattern), stdin) == NULL){  
        fprintf(stderr, "Invalid input pattern!\n");  
        exit(-1);  
      }  
      pattern[strlen(pattern)-1]='\0';  
      for(i=0;i<strlen(pattern);i++){  
        pat_val=pat_val+pattern[i]; //ascii value of pattern  
      }  
   int ch= 0;  
   printf("\n");  
   //Get char by char from file  
      while ( (ch = fgetc(file)) != EOF ){  
     buffer[j]=ch;  
     j++;  
     find(&buffer,&pattern);  
       
      }  
      if(!found_f){  
     printf("No matching sub string found in forword comparition\n");  
   }  
   if(!found_r){  
     printf("No matching sub string found in reverse comparition\n");  
   }  
   //for(i=0;i<sz;i++){  
   //  printf("%c",buffer[i]);  
   //}  
   found_f=0;  
   found_r=0;  
   pat_val=0;  
   printf("\n");    
      fclose(file);  
  }  
   return 0;  
 }  
   
 int find(char *buffer,char *pattern){  
   int i=0,k=0,l=0;  
   if(strlen(buffer)<strlen(pattern)){  
     return 0;  
   }  
   else{  
     for(i=strlen(buffer)-strlen(pattern);i<strlen(buffer);i++){  
       int key=0;  
       for(k=i;k<(strlen(pattern)+i);k++){  
         key=key+buffer[k]; //ascii value of key  
       }  
       if(key==pat_val){  
         int m=0,n=0;  
         //Forword comparition  
         for(l=0;l<strlen(pattern);l++){  
           if(pattern[l]==buffer[i+l]){  
             n++;  
           }  
           else{  
             break;  
           }  
         }  
         if(n==strlen(pattern)){  
           printf("Matching sub string found in forword signal in %d possition.\n",i+1);  
           found_f=1;  
         }  
         n=0;  
         //Reverse comparition  
         for(l=strlen(pattern)-1;l>=0;l--,m++){  
           if(pattern[l]==buffer[i+m]){  
             n++;  
           }  
           else{  
             break;  
           }  
         }  
         if(n==strlen(pattern)){  
           printf("Matching sub string found in reverse signal in %d possition.\n",i+m);  
           found_r=1;  
         }  
       }  
     }  
   }  
 }  

Boyer Moore Algorithm Using Bad Character Rule In C

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 #include <stdio.h>  
 #include <stdlib.h>  
 #include <string.h>  
 #include <errno.h>  
   
 int boyer_moore();  
   
 char pattern[256]={0};  
   
 int main (){  
   int i=0;  
   char filename[256] = {0};  
   //Get text file  
   printf("Enter path of file to read: ");  
      if (fgets(filename, sizeof(filename), stdin) == NULL){  
        fprintf(stderr, "Invalid input!\n");  
        exit(-1);  
      }  
   
   filename[strlen(filename) - 1] = '\0';  
   FILE *file = fopen(filename, "r");  
     if (!file){  
        fprintf(stderr, "Unable to open %s: %s\n",  
        filename, strerror(errno));  
        exit(-1);  
   }  
   //Get file size  
   fseek(file, 0L, SEEK_END);  
   int sz = ftell(file);  
   fseek(file, 0L, SEEK_SET);  
   //printf("size = %d",sz);  
   //create file size array  
   char buffer[sz];  
   for(i=0;i<sz;i++){  
     buffer[i]=0;  
   }  
   //Get pattern  
   printf("Enter pattern to check : ");  
      if (fgets(pattern, sizeof(pattern), stdin) == NULL){  
        fprintf(stderr, "Invalid input pattern!\n");  
        exit(-1);  
      }  
   pattern[strlen(pattern)-1]='\0';  
      int ch, word = 0;  
      i=0;  
      //put file in to array  
      while ( (ch = fgetc(file)) != EOF ){  
     buffer[i]=ch;  
     i++;  
      }  
   for(i=0;i<sz;i++){  
     printf("%c",buffer[i]);  
   }  
   printf("\n");    
      fclose(file);  
   brute_force(buffer);  
   boyer_moore(buffer);    
     return 0;  
 }  
   
 int boyer_moore(char *buffer){  
   int k=0,j=0,i=0,charcmp=0;  
   if(buffer[i]=='\0'){  
     printf("please choose a file to search\n");  
     return 0;  
   }  
   if(strlen(pattern)==0){  
     printf("please enter a pattern\n");  
     return 0;  
   }  
   if(strlen(buffer)<strlen(pattern)){  
     printf("No matching sub string found");  
     return 0;  
   }  
   printf("Boyer Moore Algorithm (Using extended bad character rule)::\n");  
   i=j=k=strlen(pattern)-1;  
   int l,found=0,not_found=1;  
   while(j<strlen(buffer)){  
     charcmp++;  
     //bad char not found  
     if(pattern[k]==buffer[i]){  
       k--; i--;  
       if(k==-1){  
         printf("\tFound matching substring at %d possition.\n",i+2);  
         j=j+strlen(pattern);  
         i=j;  
         k=strlen(pattern)-1;  
         found=1;  
       }  
     }  
     //bad char found  
     else{  
       int m=0;  
       if(k<1){  
         m=1;  
       }  
       else{  
         for(l=k-1;l>=0;l--){  
           charcmp++;  
           if(buffer[i]==pattern[l]){  
             m++;  
             not_found=0;  
             break;  
           }      
           m++;  
         }  
       }  
       j=j+m;  
       i=j;  
       k=strlen(pattern)-1;  
     }  
   }  
   if(!found){  
     printf("\tNo matching sub string found\n");  
   }  
   printf("\n\tNo of character comparitions = %d\n",charcmp);  
 }   

Brute Force String Matching Algorithm In C

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 #include <stdio.h>  
 #include <stdlib.h>  
 #include <string.h>  
 #include <errno.h>  
   
 int brute_force();  
   
 char pattern[256]={0};  
   
 int main (){  
   int i=0;  
   char filename[256] = {0};  
   //Get text file  
   printf("Enter path of file to read: ");  
      if (fgets(filename, sizeof(filename), stdin) == NULL){  
        fprintf(stderr, "Invalid input!\n");  
        exit(-1);  
      }  
   
   filename[strlen(filename) - 1] = '\0';  
   FILE *file = fopen(filename, "r");  
     if (!file){  
        fprintf(stderr, "Unable to open %s: %s\n",  
        filename, strerror(errno));  
        exit(-1);  
   }  
   //Get file size  
   fseek(file, 0L, SEEK_END);  
   int sz = ftell(file);  
   fseek(file, 0L, SEEK_SET);  
   //printf("size = %d",sz);  
   //create file size array  
   char buffer[sz];  
   for(i=0;i<sz;i++){  
     buffer[i]=0;  
   }  
   //Get pattern  
   printf("Enter pattern to check : ");  
      if (fgets(pattern, sizeof(pattern), stdin) == NULL){  
        fprintf(stderr, "Invalid input pattern!\n");  
        exit(-1);  
      }  
   pattern[strlen(pattern)-1]='\0';  
      int ch, word = 0;  
      i=0;  
      //put file in to array  
      while ( (ch = fgetc(file)) != EOF ){  
     buffer[i]=ch;  
     i++;  
      }  
   for(i=0;i<sz;i++){  
     printf("%c",buffer[i]);  
   }  
   printf("\n");    
      fclose(file);  
   brute_force(buffer);  
   boyer_moore(buffer);    
     return 0;  
 }  
   
 int brute_force(char *buffer){  
   int k=0,charcmp=0,j=0,i=0;  
   if(strlen(buffer)==0){  
     printf("please choose a file to search\n");  
     return 0;  
   }  
   if(strlen(pattern)==0){  
     printf("please enter a pattern\n");  
     return 0;  
   }  
   if(strlen(buffer)<strlen(pattern)){  
     printf("No matching sub string found");  
     return 0;  
   }  
   printf("Brute Force Algorithm ::\n");  
   while(i<strlen(buffer)){  
     charcmp++;  
     if(pattern[k]==buffer[i]){  
       k++; i++;  
       continue;  
     }  
     else if(pattern[k]=='\0'){  
       printf("\tFound matching substring at %d possition .\n",(i+1-strlen(pattern)));  
       k=0; j=1;  
     }  
     else{  
       i++; k=0; charcmp++;  
     }  
   }  
     if(!j){  
     printf("\tNo matching substring found\n");  
   }  
   printf("\n\tNo of character comparitions = %d \n",charcmp);  
   return 0;  
 }  

Graeffe's Root Squaring Method Using C

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 #include<stdio.h>  
 #include<stdlib.h>  
 #include<math.h>  
   
 int graeff();  
 int main(){  
   char status[10]={0};  
   int power;  
   system("clear");  
   printf("**********************************************\n");  
   printf("\tGRAEFF'S ROOT SQUARING METHOD\n");  
   printf("**********************************************\n");  
   while(1){  
     graeff(atoi(status));  
   }      
 }  
   
 int graeff(){  
   int power,ctr,ctr1,ctr2,ctr3,i;  
     float temp=0,div=0.5,tolerance=0;  
   printf("\nEnter the Highest Power Of Polynomial (0 to exit) = ");  
     scanf("%d",&power);  
     if(power==0){  
       system("clear");  
       printf("\n\n\tTHANK YOU\n\n\n");  
       exit(0);  
     }  
     if(power<0){  
       printf("ERROR: Can not find root for minus power!!!\n");  
       return 0;  
     }  
     
   double coe[power+1],min_coe[power+1],new_coe[2*(power+1)-1],func[power+1],o_ans[power+1],n_ans[power+1];  
   for(i=0;i<=power;i++){  
     coe[i]=0;func[i]=0;min_coe[i]=0;o_ans[i]=0;n_ans[i]=0;  
   }  
   for(ctr=0;ctr<=2*power;ctr++){  
     new_coe[i]=0;  
   }  
   for(ctr=power;ctr>=0;ctr--){  
       printf("Enter the coefficient of power %d = ",ctr);  
       scanf("%lf",&coe[ctr]);  
   }  
   for(ctr=power;ctr>=0;ctr--){  
     func[ctr]=coe[ctr];  
   }  
   printf("\nEnter the Error Tolerance = ");  
     scanf("%f",&tolerance);  
   printf("\n");  
   i=1;  
   int j=1;  
     while(i){  
     //printf("Now coefficient values accoroding to the power\n");  
     //for(ctr=power;ctr>=0;ctr--){  
     //  printf("\t%dth power coefficient = %f\n",ctr,coe  
     //            [ctr]);  
     //}  
     printf("\niteration %d\n",j);  
     j++;  
     for(ctr=power;ctr>=0;ctr--){  
       min_coe[ctr]=coe[ctr];  
     }  
     for(ctr=power-1;ctr>=0;ctr=ctr-2){  
       min_coe[ctr]=(-1*min_coe[ctr]);  
     }  
     ctr2=2*power;  
     ctr3=2*power;  
     for(ctr=power;ctr>=0;ctr--){  
       for(ctr1=power;ctr1>=0;ctr1--,ctr2--){  
         new_coe[ctr2]=new_coe[ctr2]+  
             (coe[ctr]*min_coe[ctr1]);  
       }  
       ctr3--;  
       ctr2=ctr3;  
     }  
     for(ctr=power,ctr2=2*power;ctr>=0,ctr2>=0;ctr2=ctr2-2,ctr--){  
       coe[ctr]=new_coe[ctr2];  
     }  
     for(ctr=0;ctr<=2*power;ctr++){  
       new_coe[ctr]=0;  
     }  
     for(ctr=0;ctr<power;ctr++){  
         temp=fabs(coe[ctr])/fabs(coe[ctr+1]);  
         n_ans[ctr]=pow(temp,div);  
       }  
       printf("\tRoots: ");  
       for(ctr=0;ctr<power;ctr++){  
           printf("\t%f",n_ans[ctr]);  
       }  
       printf("\n\tError: ");  
       for(ctr=0;ctr<power;ctr++){  
           printf("\t%f",(n_ans[ctr]-o_ans[ctr])/o_ans[ctr]);  
       }  
       int count=0;  
       for(ctr=0;ctr<power;ctr++){  
         if((n_ans[ctr]-o_ans[ctr])/n_ans[ctr]<=tolerance){  
           count++;  
         }  
         if(j==51){  
           printf("\nRoots are not identified!!!\n");  
           return 0;  
         }  
         o_ans[ctr]=n_ans[ctr];  
         if(count==power){  
           i=0;  
         }  
       }      
     printf("\n");  
       div=div/2;  
     }  
     for(ctr=0;ctr<=power;ctr++){  
     coe[ctr]=0;  
   }  
     printf("\n");  
   for(ctr=0;ctr<power;ctr++){    
     float x1=o_ans[ctr];  
     float x2=-1*(o_ans[ctr]);      
     float y1=0;  
     float y2=0;  
     for(ctr1=0;ctr1<=power;ctr1++){      
       y1+=pow(x1,ctr1)*func[ctr1];  
     }  
     printf("When %f function = %f\t",x1,y1);  
     for(ctr1=0;ctr1<=power;ctr1++){      
       y2+=pow(x2,ctr1)*func[ctr1];  
     }  
     printf("When %f function = %f\n\n",x2,y2);  
   }  
   for(i=0;i<=power;i++){  
     coe[i]=0;func[i]=0;min_coe[i]=0;o_ans[i]=0;n_ans[i]=0;  
   }  
   for(ctr=0;ctr<=2*power;ctr++){  
     new_coe[i]=0;  
   }  
     
 }  

Radix Sort Using Java

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 import java.util.*;  
 class radix {  
   //Start counting time.  
   long start = System.nanoTime();  
   public static String[] RadixSort(long[] a) {  
     // convert from long to String  
     String[] s = new String[a.length];  
     for (int i = 0; i < a.length; i++) {  
       s[i] = Long.toString(a[i]);  
     }  
     // get the length of the longest number  
     int l = 0;  
     for (int i = 0; i < s.length; i++) {  
       int current = s[i].length();  
       if (current > l) {  
         l = current;  
       }  
     }  
     // add empty spaces to make the data of equal length  
     String current3 = "";  
     for (int i = 0; i < s.length; i++) {  
       int current2 = s[i].length();  
       for (int j = 1; j <= l-current2; j++) {  
         current3 += " ";  
       }  
       current3 += s[i];  
       s[i] = current3;  
       current3 = "";  
     }  
     // create the buckets  
     String[] tmp1 = new String[s.length];  
     String[] tmp2 = new String[s.length];  
     int tmp1i = 0;  
     int tmp2i = 0;  
     // sort the array  
     for (int i = l; i >= 1; i--) {  
       for (int j = 0; j < s.length; j++) {  
         String current = s[j].substring(i-1, i);  
         if (current.equals(" ") || current.equals("0")) {  
           tmp1[tmp1i] = s[j];  
           tmp1i++;  
         }  
         else {  
           tmp2[tmp2i] = s[j];  
           tmp2i++;  
         }  
       }  
       for (int j = 0; j < tmp1i; j++) {  
         s[j] = tmp1[j];  
       }  
       for (int j = 0; j < tmp2i; j++) {  
         int track = tmp1i;  
         s[track] = tmp2[j];  
         track++;  
       }  
       tmp1i = 0;  
       tmp2i = 0;  
     }  
     return s;  
   }  
   long end = System.nanoTime();  
   //end counting time.  
 }  
 public class radixsort{  
   public static void radixsort() {  
     Scanner scan = new Scanner(System.in);  
     System.out.print("How many values would you like to sort? ");  
     int length = scan.nextInt();  
     long[] a = new long[length];  
     for (int i = 0; i < length; i++) {  
       System.out.print("Enter "+ (i+1)+ " number: ");  
       a[i] = scan.nextLong();  
     }  
     radix r=new radix();  
     r.RadixSort(a);  
     //String[] s = new String[a.length];  
     //s = RadixSort(a);  
     for (int i = 0; i < a.length; i++) {  
       System.out.println(a[i]);  
     }  
     long elapsedTime = r.end - r.start;  
     System.out.println("Running time of heap sort ="+elapsedTime + " nano seconds");  
   }  
 }  

Shell Sort Using Java

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 import java.util.*;  
   
 class shell{  
   //Start counting time.  
   long start = System.nanoTime();  
   public static void shell(int[] a) {  
     int increment = a.length / 2;  //select partitions.  
     //System.out.println("\n"+"increment is "+increment+"\n");  
     while (increment > 0) {  
       System.out.println("increment is "+increment);  
       for (int i = increment; i < a.length; i++) { //select elements and sort.  
         int j = i;  
         int temp = a[i];  
         while (j >= increment && a[j - increment] > temp) { //sort selected elements.  
           a[j] = a[j - increment];  
           j = j - increment;  
   
         }  
         a[j] = temp;  
       }  
       increment=increment/2; //partition the array again  
     }  
   }  
   long end = System.nanoTime();  
   //end counting time.  
 }  
 public class shellsort{  
   public static void shellsort(){  
     System.out.println("");  
     Scanner scan=new Scanner(System.in);  
     try{  
       System.out.print("Enter number of elements you want to sort :");  
       int length=scan.nextInt();  
       int[] arr=new int[length];  
       //System.out.println("Enter integer values you want to sort :");  
       for(int i=0;i<arr.length;i++){  
         System.out.print("Enter "+ (i+1)+ " number: ");  
         arr[i]=scan.nextInt();  
       }  
       shell sh=new shell();  
       sh.shell(arr);  
       System.out.println("\n"+ "Sorted values :");  
       for(int j=0;j<arr.length;j++){  
         System.out.print(arr[j]+",");  
       }  
       System.out.println("");  
       long elapsedTime = sh.end - sh.start;  
       System.out.println("\n"+"Running time of heap sort ="+elapsedTime + " nano seconds"+"\n");  
     }catch(Exception e){  
       System.out.println("Error in input");  
     }  
   }  
   
 }  

Quick Sort Using Java

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 import java.util.*;  
   
 class quick{  
   public void quickSort(int array[]){  
 // the array is sorted in ascending order  
     quickSort(array, 0, array.length - 1);       // quicksort all the elements in the array  
   }  
   
   //Start counting time.  
   long start = System.nanoTime();  
   public void quickSort(int array[], int start, int end){  
       int i = start;             // index of left-to-right scan  
       int k = end;              // index of right-to-left scan  
   
       if (end - start >= 1){          // check that there are at least two elements to sort  
           int pivot = array[start];    // set the pivot as the first element in the partition  
       System.out.println("\n"+"pivot value : "+pivot);  
           while (k > i){          // while the scan indices from left and right have not met,  
               while (array[i] <= pivot && i <= end && k > i) // from the left, look for the first  
                   i++;                  // element greater than the pivot  
                 while (array[k] > pivot && k >= start && k >= i) // from the right, look for the first  
                   k--;                    // element not greater than the pivot  
               if (k > i)                    // if the left seekindex is still smaller than  
                   swap(array, i, k);           // the right index, swap the corresponding elements  
           }  
           swap(array, start, k);     // after the indices have crossed, swap the last element in  
           for(int j=0;j<array.length;j++){  
         System.out.print(array[j]+",");  
       }  
       System.out.println("");     
           quickSort(array, start, k - 1); // quicksort the left partition  
           quickSort(array, k + 1, end);  // quicksort the right partition  
       }  
         else{  // if there is only one element in the partition, do not do any sorting  
           return;           // the array is sorted, so exit  
         }  
   }  
   
   public void swap(int array[], int index1, int index2){  
   // the values at indices 1 and 2 have been swapped  
     int temp = array[index1];      // store the first value in a temp  
     array[index1] = array[index2];   // copy the value of the second into the first  
     array[index2] = temp;        // copy the value of the temp into the second  
   }  
   long end = System.nanoTime();  
   //end counting time.  
 }  
   
 public class quicksort{  
   public static void quicksort(){  
     System.out.println("");  
     Scanner scan=new Scanner(System.in);  
     try{  
       System.out.print("Enter number of elements you want to sort :");  
       int length=scan.nextInt();  
       int[] arr=new int[length];  
       //System.out.println("Enter integer values you want to sort :");  
       for(int i=0;i<arr.length;i++){  
         System.out.print("Enter "+ (i+1)+ " number: ");  
         arr[i]=scan.nextInt();  
       }  
       quick q=new quick();  
       q.quickSort(arr);  
       System.out.println("\n"+"Entered values after Sort :");  
       for(int j=0;j<arr.length;j++){  
         System.out.print(+arr[j]+",");  
       }  
       long elapsedTime = q.end - q.start;  
       System.out.println("");  
       System.out.println("\n"+"Running time of heap sort ="+elapsedTime + " nano seconds"+"\n");  
     }catch(Exception e){  
       System.out.println("Error in input");  
     }  
   }  
 }