Introduction to Computer Science - Exercise 5

Name: Saggi Mizrahi • ID: 032493124 • Group: מעוף א'Date: November 18, 2013


Functions

3.

Code:

/* polyverse.cpp
 * This program prints out the input number reversed and whether it's a
 * palindrome.
 *
 * Saggi Mizrahi 18 November 2013
 */
#include <iostream>

using namespace std;

int reverse(int num);
bool isPalindrome(int num);

// reverse a number
int reverse(int num) {
    int result = 0;
    for (int tmp = num; tmp > 0; tmp /= 10) {
        result *= 10;
        result += tmp % 10;
    }

    return result;
}

// determine if a number is a palindrome
bool isPalindrome(int num) {
    return num == reverse(num);
}

/* Prints out the input number reversed and whether it's a
 * palindrome.
 * Input: a number.
 * Output: the number reversed and whether it's a palindrome.
 */
int main()
{
    // declate variables
    int num;

    // get user input
    cout << "please enter a number: ";
    cin >> num;

    // output the results
    cout << "The number reversed is: " << reverse(num) << endl;

    cout << "The number is ";
    if (!isPalindrome(num)) {
        cout << "not ";
    }
    cout << "a palindrome" << endl;
    return 0;
}

Outputs:

please enter a number: 123
The number reversed is: 321
The number is not a palindrome

please enter a number: 30
The number reversed is: 3
The number is not a palindrome

please enter a number: 12321
The number reversed is: 12321
The number is a palindrome

4.

Code:

/* digicount.cpp
 * This program prints out the sum of the digit count.
 *
 * Saggi Mizrahi 18 November 2013
 */
#include <iostream>

using namespace std;

// error codes
const int NEGATIVE_INPUT_NUMBER = -1;
const int ILLIGAL_DIGIT = -2;
const int NEGATIVE_DIGITS = -3;
const int DIGITS_NOT_UNIQUE = -4;


// function declerations
int countDigit(int num, int digit);
bool uniqueDigits(int num);
int countDigits(int num, int digits);


// counts the number of times a single digit appears in a number.
int countDigit(int num, int digit) {
    int digitCounter = 0;

    // check digit
    if (digit < 0 || digit > 9) {
        return ILLIGAL_DIGIT;
    }

    // check num
    if (num <= 0) {
        return NEGATIVE_INPUT_NUMBER;
    }

    // count digit
    for (int tmp = num; tmp > 0; tmp /= 10) {
        if ((tmp % 10) == digit) {
            digitCounter++;
        }
    }

    return digitCounter;
}

// returns whether a number only contains unique digits.
bool uniqueDigits(int num) {
    int digit = -1;

    for (int tmp = num; tmp > 0; tmp /= 10) {
        digit = (tmp % 10);
        if (countDigit(tmp, digit) > 1) {
            return false;
        }
    }

    return true;
}

// counts multiple digits in a number.
int countDigits(int num, int digits) {
    int digit = -1;
    int sum = 0;

    // check digits
    if (digits <= 0) {
        return NEGATIVE_DIGITS;
    }

    if (!uniqueDigits(digits)) {
        return DIGITS_NOT_UNIQUE;
    }

    // check num
    if (num <= 0) {
        return NEGATIVE_INPUT_NUMBER;
    }

    // caluclate result
    for (int tmp = digits; tmp > 0; tmp /= 10) {
        digit = tmp % 10;
        sum += countDigit(num, digit);
    }

    return sum;
}

/* Prints out the sum of the digit count.
 *
 * Input: a number and a sequence of digits.
 * Output: the sum of all counted digits.
 */
int main()
{
    // declare variables
    int num = -1;
    int digits = -1;
    int rc = 0;

    // get user input
    cout << "please enter a number: ";
    cin >> num;
    cout << "please enter a sequence of digits: ";
    cin >> digits;

    switch ((rc = countDigits(num, digits))) {
        case DIGITS_NOT_UNIQUE:
            cout << "Invalid input, sequence of digits " <<
                "contains duplicates" << endl;
            break;
        case NEGATIVE_INPUT_NUMBER:
            cout << "Invalid input, input number is not "
                "positive" << endl;
            break;
        case NEGATIVE_DIGITS:
            cout << "Invalid input, input digits is not "
                "positive" << endl;
            break;
        default: // success
            cout << "Sum of digit count: " << rc << endl;
    }

    return (rc < 0) ? rc : 0;
}

Outputs:

please enter a number: 122423
please enter a sequence of digits: 21
Sum of digit count: 4

please enter a number: 122423
please enter a sequence of digits: 121
Invalid input, sequence of digits contains duplicates

please enter a number:  -122423
please enter a sequence of digits: 21
Invalid input, input number is not positive

please enter a number: 122423
please enter a sequence of digits:  -21
Invalid input, input digits is not positive

5.

Code:

/* digicount.cpp
 * This program prints out a number which is the input number reordered
 * according to a sequence of indices.
 *
 * Saggi Mizrahi 18 November 2013
 */
#include <iostream>
#include <math.h>

using namespace std;

// error codes
const int INDEX_OUT_OF_RANGE = -1;
const int NEGATIVE_NUMBER = -2;
const int NEGATIVE_INDICES = -3;
const int INDICES_TOO_LONG = -4;
const int NUMBER_TOO_LONG = -5;

// max values
const int NUM_MAX = 999999999;
const int INDICES_MAX = 999999999;


// function declerations
int indexSwap(int num, int indices);
int digitAtIndex(int num, int index);
int countDigits(int num);
int reverse(int num);


// counts the number of times a single digit appears in a number.
int indexSwap(int num, int indices) {
    int digit = -1;
    int index = -1;

    int digitCount = -1;
    int res = 0;

    if (num < 0) {
        return NEGATIVE_NUMBER;
    }

    if (indices < 0) {
        return NEGATIVE_INDICES;
    }

    if (num > NUM_MAX) {
        return NUMBER_TOO_LONG;
    }

    if (indices > INDICES_MAX) {
        return INDICES_TOO_LONG;
    }

    digitCount = countDigits(num);

    for(int tmp = indices; tmp > 0; tmp /= 10) {
        digit = tmp % 10;
        index = digitCount - digit - 1;
        if (index >= digitCount) {
            return INDEX_OUT_OF_RANGE;
        }

        res *= 10;
        res += digitAtIndex(num, index);
    }

    res = reverse(res);
    return res;
}

// returns the digit at a specific index.
int digitAtIndex(int num, int index) {
    return int(num / pow(10, index)) % 10;
}

// counts the number of digits in a number.
int countDigits(int num) {
    int digitCounter = 0;
    for (int tmp = num; tmp > 0; tmp /= 10) {
        digitCounter++;
    }

    return digitCounter;
}

// reverses a number.
int reverse(int num) {
    int res = 0;
    for (int tmp = num; tmp > 0; tmp /= 10) {
        res *= 10;
        res += tmp % 10;
    }

    return res;
}

/* Prints out a number which is the input number reordered
 * according to a sequence of indices.
 *
 * Input: a sequence of digits and a sequence of indices.
 * Output: the numbers in the input sequence as ordered by the indices.
 */
int main()
{
    // declare variables
    int digits = -1;
    int indices = -1;
    int rc = 0;

    // get user input
    cout << "please enter a sequence of digits: ";
    cin >> digits;
    cout << "please enter a sequence of indices: ";
    cin >> indices;

    switch ((rc = indexSwap(digits, indices))) {
        case INDEX_OUT_OF_RANGE:
            cout << "Invalid input, sequence of indices " <<
                "contains an invalid index" << endl;
            break;
        case NEGATIVE_NUMBER:
            cout << "Invalid input, input number is "
                "negative" << endl;
            break;
        case NEGATIVE_INDICES:
            cout << "Invalid input, input indices number is "
                "negative" << endl;
            break;
        case INDICES_TOO_LONG:
            cout << "Invalid input, sequence of indices is too "
                "long" << endl;
            break;
        case NUMBER_TOO_LONG:
            cout << "Invalid input, sequence of digits is too "
                "long" << endl;
            break;
        default: // success
            cout << "The reordered sequence is: " << rc << endl;
    }

    return (rc < 0) ? rc : 0;
}

Outputs:

please enter a sequence of digits: 4735
please enter a sequence of indices: 2010
The reordered sequence is: 3474

please enter a sequence of digits: 3028
please enter a sequence of indices: 2010
The reordered sequence is: 2303

please enter a sequence of digits:  -3028
please enter a sequence of indices: 2010
Invalid input, input number is negative

please enter a sequence of digits: 3028
please enter a sequence of indices:  -2010
Invalid input, input indices number is negative

please enter a sequence of digits: 2002800000
please enter a sequence of indices: 2010
Invalid input, sequence of digits is too long

please enter a sequence of digits: 3000
please enter a sequence of indices: 20100000000
Invalid input, sequence of indices is too long

6.

א.

The program is going to iterate until a - 2.0 > \epsilon.
Since a=0.0 at the start and is incremented by 0.1 it's going to pass \epsilon after the 20th iteration.

Since it prints an asterisk in each iteration there are going to be 20 asterisks.

ב.

The program is going to iterate until a - 2.0 > \epsilon.
Since a=0.0 at the start and is incremented by 0.1 it's going to pass \epsilon after the 20th iteration.

In each iteration it calls asterisks(double x) which prints asterisks while x - 2.0 > \epsilon also incrementing x by 0.1 in the process.

This means that the first iteration of the main loop will print 21 asterisks the second 20 and so on.

This corrolates with a well knows series which means the amount of asterisks is going to be {n(n+1)} \over {2}

Since n=20 the solution is:
{20 \times (21 + 1)} \over 2
{20 \times 21} \over 2
420 \over 2
210

This means there's going to be 210 asterisks.

7.

Code:

/* cosine.cpp
 * This program calculates cos(x) in many different ways.
 *
 * Saggi Mizrahi 18 November 2013
 */
#include <iostream>
#include <math.h>

using namespace std;

// function declarations
double factorial(int y);
double fabsolute(double x);
double power(double x, int y);
double cos1(double x, int n);
double cos2(double x, int n);
double cos3(double x, double epsilon);

// returns x to the power of y (x^y)
double power(double x, int y) {
    int res = 1;
    for (int i = 0; i < y; i++) {
        res *= x;
    }

    return res;
}

// returns the absoloute value of x (|x|).
double fabsolute(double x) {
    return  x < 0 ? -x : x;
}

// returns the factorial of y (y!).
double factorial(int y) {
    double result = 1;
    for(int i = 2; i <= y; i++) {
        result *= i;
    }

    return result;
}

// calculates cosine slowly in n iterations.
double cos1(double x, int n) {
    double res = 1;

    for (int i = 1; i <= n; i++) {
        res += pow(-1, i) * (pow(x, 2 * i) / factorial(2 * i));
    }

    return res;
}

// calculates cosine in n iterations.
double cos2(double x, int n) {
    double res = 1;
    int multiplier = 1;
    double fac = 1;
    double p = 1;

    n *= 2;
    for (int i = 2; i <= n; i += 2) {
        multiplier *= -1;
        p *= x * x;
        fac *= (i - 1) * i;

        res += multiplier * (p / fac);
    }

    return res;
}

// calculates cosine to the margine of error 'epsilon'.
double cos3(double x, double epsilon) {
    double res = 1;
    int multiplier = 1;
    double fac = 1;
    double p = x;
    int i = 1;
    double errorMargin = 1;

    while (errorMargin >= epsilon) {
        i++;
        p *= x;
        fac *= i;
        multiplier *= -1;

        res += multiplier * (p / fac);

        i++;
        p *= x;
        fac *= i;

        errorMargin = p / fac;
    }

    return res;
}

/* Prints out the cosine of a number calculated in many different ways.
 *
 * Input: a degree in radians.
 * Output: the cosine as calculated by the different cosine functions.
 */
int main()
{
    // declare constants
    const int COS1_N = 10;
    const int COS2_N = 10;
    const double COS3_EPSILON = .0000000001;

    // declare variables
    double degree;

    // get user input
    cout << "please enter a degree in radians: ";
    cin >> degree;

    cout << "cos1(" << degree << ") -> " << cos1(degree, COS1_N) << endl;
    cout << "cos2(" << degree << ") -> " << cos2(degree, COS2_N) << endl;
    cout << "cos3(" << degree << ") -> " << cos3(degree, COS3_EPSILON) << endl;
    cout << "std::cos(" << degree << ") -> " << cos(degree) << endl;
}

Outputs:

please enter a degree in radians: 1
cos1(1) -> 0.540302
cos2(1) -> 0.540302
cos3(1) -> 0.540302
std::cos(1) -> 0.540302

please enter a degree in radians: 0
cos1(0) -> 1
cos2(0) -> 1
cos3(0) -> 1
std::cos(0) -> 1

please enter a degree in radians: 0.5
cos1(0.5) -> 0.877583
cos2(0.5) -> 0.877583
cos3(0.5) -> 0.877583
std::cos(0.5) -> 0.877583

please enter a degree in radians: 0.3
cos1(0.3) -> 0.955336
cos2(0.3) -> 0.955336
cos3(0.3) -> 0.955336
std::cos(0.3) -> 0.955336

please enter a degree in radians: 0.99999
cos1(0.99999) -> 0.540311
cos2(0.99999) -> 0.540311
cos3(0.99999) -> 0.540311
std::cos(0.99999) -> 0.540311

please enter a degree in radians: 0.000001
cos1(1e-06) -> 1
cos2(1e-06) -> 1
cos3(1e-06) -> 1
std::cos(1e-06) -> 1

8.

Code:

/* facpow.cpp
 * This program calculates factorial and power.
 *
 * Saggi Mizrahi 18 November 2013
 */
#include <iostream>

using namespace std;

// error codes
const int INVALID_INPUT = -1;

// function declarations
void factorial(int y, double& y_fact);
int power(int x, int y, double& res);

// returns x to the power of y (x^y)
int power(int x, int y, double& res) {
    if (x == 0 and y <= 0) {
        return INVALID_INPUT;
    }
    res = 1;
    int n = y < 0 ? -y : y;
    for (int i = 0; i < n; i++) {
        res *= x;
    }

    if (y < 0) {
        res = 1 / res;
    }

    return res;
}

// returns the factorial of y (y!).
void factorial(int y, double& y_fact) {
    y_fact = 1;
    for(int i = 2; i <= y; i++) {
        y_fact *= i;
    }
}

/* Takes two numbers x, y and prints out x! and x^y.
 *
 * Input: 2 numbers.
 * Output: x! and x^y.
 */
int main()
{
    // declare variables
    int x, y;
    double x_fact, x_pow;

    // get user input
    cout << "please enter 2 numbers: ";
    cin >> x >> y;

    factorial(x, x_fact);
    if (power(x, y, x_pow) < 0) {
        cout << "Invalid Input" << endl;
        return -1;
    }

    cout << x << "! = " << x_fact << endl;
    cout << x << "^" << y << " = " << x_pow << endl;

    return 0;
}

Outputs:

please enter 2 numbers: 3 2
3! = 6
3^2 = 9

please enter 2 numbers: 0 -1
Invalid Input

please enter 2 numbers: 3 -1
3! = 6
3^-1 = 0.333333

9.

Code:

/* perfectfriends.cpp
 * This program calculates perfect numbers and finds friend numbers.
 *
 * Saggi Mizrahi 18 November 2013
 */
#include <iostream>
#include <math.h>

using namespace std;

// constants
const double EPSILON = .0000000001;

// function declarations
void devisors(int y, int& num, int& sum);
bool isPerfect(int x);

// returns the number of devisors y has and their sum
void devisors(int y, int& num, int& sum) {
    num = 1;
    sum = 1;

    int n = sqrt(y) + EPSILON;
    for (int i = 2; i <= n; i++) {
        if ((y % i) == 0) {
            num += 2;
            sum += i;
            sum += y / i;
        }
    }
}

// checks if a number is equal to the sum of it's devisors
bool isPerfect(int x) {
    int num, sum;
    devisors(x, num, sum);
    return x == sum;
}

/* Takes an input number M and prints all the perfect numbers and friendly
 * paris between 2 and M
 *
 * Input: a number.
 * Output: All the perfect numbers and friendly pairs in range.
 */
int main()
{
    // declare variables
    int m = -1;
    int num, sum, sum2;

    // get user input
    cout << "please enter a number: ";
    cin >> m;

    for (int i = 2; i <= m; i++) {
        devisors(i, num, sum);
        if (sum == i) {
            cout << i << " is perfect" << endl;
        } else if (sum > i && sum <= m) {
            devisors(sum, num, sum2);
            if (sum2 == i) {
                cout << i << " and " << sum <<
                    " are friends" << endl;
            }
        }
    }
}

Outputs:

please enter a number: 300
6 is perfect
28 is perfect
220 and 284 are friends

please enter a number: 3000
6 is perfect
28 is perfect
220 and 284 are friends
496 is perfect
1184 and 1210 are friends
2620 and 2924 are friends

please enter a number: 30000
6 is perfect
28 is perfect
220 and 284 are friends
496 is perfect
1184 and 1210 are friends
2620 and 2924 are friends
5020 and 5564 are friends
6232 and 6368 are friends
8128 is perfect
10744 and 10856 are friends
12285 and 14595 are friends
17296 and 18416 are friends

Arrays

1.a.א.

Yes!

1.b.א.

Yes!

2.

Code:

/* arrmin.cpp
 * This program prints out the indices of the minimal number in an array.
 *
 * Saggi Mizrahi 18 November 2013
 */
#include <iostream>

using namespace std;

/* Prints out the indices of the minimal number in an array.
 *
 * Input: 12 numbers.
 * Output: the indices of the minimal number in an array.
 */
int main()
{
    // declare constants
    const int SIZE = 12;
    // declare variables
    int nums[SIZE];
    int min;

    // get user input
    cout << "please enter 12 numbers: ";
    cin >> nums[0];
    min = nums[0];
    for (int i = 1; i < SIZE; i++) {
        cin >> nums[i];
        if (nums[i] < min) {
            min = nums[i];
        }
    }

    // output the results
    for (int i = 0; i < SIZE; i++) {
        if (nums[i] == min) {
            cout << i << " ";
        }
    }
    cout << endl;
}

Outputs:

please enter 12 numbers: 6 14 12 14 12 4 14 6 4 12 4 14
5 8 10