// Arup Guha
// 10/31/2011
// Written in COP 3223 Class

#include <stdio.h>

double my_sqrt(double n);
int numDistinct(int values[], int length);
double sumSqrt(int n);

int main() {


    int n;
    printf("How many rows do you want in your multiplication table?\n");
    scanf("%d", &n);

    // Reset n if necessary.
    if (n <= 0)
        n = 10;

    char filename[20];
    printf("What file do you want the output?\n");
    scanf("%s", filename);

    FILE* ofp = fopen(filename, "w");

    int val1, val2;
    for (val1 = 1; val1 <=n; val1++) {

        for (val2 = 1; val2 <= n; val2++)
            fprintf(ofp, "%4d", val1*val2);
        fprintf(ofp, "\n");
    }

    fclose(ofp);

    printf("The square root of 53 is %lf\n", my_sqrt(my_sqrt(5)+3)+my_sqrt(9));



    int array[] = {1, 2, 2, 2, 2, 2, 3, 3, 1, 9, 2, 2, 2, 1, 2, 1, 2};

    printf("There are %d different values\n", numDistinct(array, 17));

    printf("Sum is %lf\n", sumSqrt(2000));

    return 0;
}

// Pre-condition: n > 0
// Post-condition: Returns the square root of n within .0001.
double my_sqrt(double n) {

    // Establish our search bounds.
    double low = 1, high = n;
    if (n < 1) {
        low = n;
        high = 1;
    }

    double mid = (low+high)/2;

    // Keep on searching until our guess is pretty good.
    while (fabs(n - mid*mid) > 0.000000001) {
        if (mid*mid > n)
            high = mid;
        else
            low = mid;
        mid = (low+high)/2;
    }

    return mid;
}


// Pre-condition: values only contains numbers 1 through 10, inclusive and has length length.
// Post-condition: Returns the number of different values in the array values.
int numDistinct(int values[], int length) {

    int freq[11];

    // Initialize the frequency array.
    int i;
    for (i=0; i<11; i++)
        freq[i] = 0;

    // Fill the frequency array with how many of each item
    // there is.
    for (i=0; i<length; i++) {
        int my_value = values[i];
        freq[my_value]++;

    }

    // See how many different items there were.
    int cnt =0;
    for (i=1; i<11; i++)
        if (freq[i] > 0)
           cnt++;

    return cnt;
}

// Pre-condition: n is non-negative.
// Post-condition: Returns the sum sqrt(1)+sqrt(3)+...+sqrt(2n+1).
double sumSqrt(int n) {

    double sum = 0;

    int i;
    for (i=1; i <= 2*n+1; i = i+2) {
        sum = sum + my_sqrt(i);
    }
    return sum;
}
