Thursday, 18 December 2014

Determining the number of square integers (perfect squares) between any given range.

/*Square integer is a integer which is a perfect square of any integer. In this , I have tried this with 2 possible solutions*/

1st solution (brute force method):-

#include<stdio.h>
#include<math.h>
int main(){
    int n;
    long t,a,b;
    int i,count=0;
    printf("Enter number of test cases\n");//number of ranges
    scanf("%d",&n);
    while(n>0){
        count=0;
        scanf("%d%d",&a,&b);
        for(i=a;i<=b;i++){
            t=sqrt(i);/*function to determine square root of any given number;*/
           
            if(t*t==i)/*checking if this particular number is perfect square*/

            count++;
           
        }
        n--;
    printf("%d\n",count);
    }
}

2nd solution (one of the best(optimized way) to determine if number is perfect square or not):-

#include<stdio.h>
#include<math.h>
int main(){
    int n,a,b;
    int count=0;
    printf("Enter number of test cases\n");//number of ranges
    scanf("%d",&n);
    while(n>0){
        scanf("%d%d",&a,&b);
        count=floor(sqrt(b))-ceil(sqrt(a))+1;/*optimized way to calculate all perfect squares b/w a &&b;*/
 
        printf("%d\n",count);
        n--;
    }

o/p:-
Enter number of test cases
2
3 9
2 /*between 3 and 9 (inclusive) only 2 numbers are perfect squares--4 and 9*/

17 24
0

Tuesday, 16 December 2014

To print every pass of an insertion sort (ready to run) in c

/* First let me tell you some basic about insertion sort (for those who wants to refresh there concepts). Its a sorting technique which have a time complexity in worst case as O(n*n) an best case is O(n);*/
/*also i did not utilize the argument of printArr() ,which can be utilized for displaying and knowing the pass number*/
#include<stdio.h>
#include<math.h>
int n,arr[10];
//function to print the elements in the array
void printArr(int a){
    int j;
    for(j=0;j<n;j++)
    printf(" %d",arr[j]);
}

int main(){
    int i,j,k;
    printf("Enter number of elements");
    scanf("%d",&n);
//taking input
    for(i=0;i<n;i++){
        printf("Enter element %d",i+1);
        scanf("%d",&arr[i]);
       }

printArr(0);//simply print input array
//doing the insertion sort and displaying every pass result
for(i=0;i<n;i++){
        k=arr[i];
        j=i-1;
        while(j>=0&&k<arr[j]){
            arr[j+1]=arr[j];
            j--;
        }
        arr[j+1]=k;
        printf("\n");
        printArr(i+1);
    }
return 0;
}