Homework 10: Babylonian Method

This function will calculate a square root through the Babylonian Method.

First of all, I would like to explain how the method works. You have to establish a first number that is “aproximate” to the real squareroot, doesn’t matter if that number is equal to one, because we are going to make some mathematical operations. Shown below the steps.

  1. Divide the number, which we want to calculate its square root (N), between the before established number (y).
  2. The result of the past step will be added to the first established number (y).
  3. We repeat this steps until we obtain the aproximation as exactly as we want it.

Having said that, we only have to create a function that execute this algorithm, and ask the user for the number that he/she wants to calculate its square root.

This is my code.

#include <iostream>
using namespace std;

long double square_root(long double N)
{
  long double y=1, c;
  for(int i=0; i<1000; i++)
  {
    c=N/y;
    y=(y+c)/2;
  }
  return y;
}

int main()
{
  int N;
  cout << "Square Root... \n\nNumber: ";
  cin >> N;
  cout << "The square root of "<< N << " is equal to "<<square_root(N) << endl << endl;
  return 0;
}

 

Quiz week 11: Partial #2 Review

The teacher gave us a document with 10 problems to solve. This with the objective of practicing the topics that we have seen during the semester.

 

Exercise 1:

Write a function that calculates the distance between two points in a coordinate plane. I used the Pythagoras theorem.

#include <iostream>
#include <math.h>
using namespace std;

float distancia(float x1,float y1,float x2,float y2)
{
  float D;
  D = sqrt(pow((x2-x1),2)+pow((y2-y1),2));
  return D;
}

int main()
{
  float x1, x2, y1, y2;
  cout << "X1= ";
  cin >> x1;
  cout << "Y1= ";
  cin >> y1;
  cout << "X2= ";
  cin >> x2;
  cout << "Y2= ";
  cin >> y2;

  cout << distancia(x1,y1,x2,y2) << endl;
  return 0;
}

 

Exercise 2:

A program that prints a triangle with a given size. I utilized nested for’s to print each character line by line.

#include <iostream>
#include <stdio.h>
using namespace std;

void triangle(int S)
{
  for (int c=1 ; c<=S ; c++)
  {
      for(int i=c ; i>0; i--)
      {
        printf("T");
      }
      printf("\n");
  }
  for (int c=S-1 ; c>0 ; c--)
  {
    for(int i=c ; i>0 ; i--)
    {
      printf("T");
    }
    printf("\n");
  }
}

int main()
{
  int S;
  cout << "\n\nSize: ";
  cin >> S;
  cout << "\n\n\n\n";
  triangle(S);
  cout << "\n\n\n\n";

  return 0;
}

 

Exercise 3:

A program that calculates factorial numbers. I used unsigned long int as the type of the result because the factorial operation only gives integer and positive numbers. I used conditionals to mark errors and a for to multiply numbers, and then substract an unit.

#include <iostream>
using namespace std;

unsigned long int factorial(int N)
{
  unsigned long int F=1;
  if (N<0)
    cout << "Math error!" << endl;

  else if (N==0)
    F=1;

  else
  {
    for (int c=N; c>0; c--)
      F*=c;
  }

  return F;
}

int main()
{
  int N;
  cin >> N;
  cout << N <<"! = " << factorial(N) << endl;

  return 0;
}

 

Exercise 4:

A function that receives a list of numbers and calculates their average. I ask for the quantity of number that will be introduced, to declare the vector. Then I read each one and introduce the vecor in a function called promedio_lista. Then I just sum the numbers with a for and divide them by the quantity of them.

#include <iostream>
using namespace std;

float promedio_lista(float calf[], int N)
{
  float P=0;
  for (int c=0; c<N; c++)
    P+=calf[c];
  P/=N;

  return P;
}

int main()
{
  int N;
  cout << "\n\n\n¿Cuantas calificaciones vas a introducir? ";
  cin >> N;
  float calf[N];
  cout << "\n\n";

  for (int c=0; c<N; c++)
  {
    cout << "Calificación " << c+1 << ": ";
    cin >> calf[c];
  }

  cout << "\nPromedio= " << promedio_lista(calf, N) << "\n\n";

  return 0;
}

 

Exercise 5:

A function that detect the smallest number in a list of four numbers. To make this, I established that one of them were the smallest and then make comparisons with conditionals.

#include <iostream>
using namespace std;

float smallest_of_four(float a, float b, float c, float d)
{
  float m=a;
  if (b<m)
    m=b;
  else if (c<m)
    m=c;
  else if (d<m)
    m=d;

  return m;
}

int main()
{
  float a, b, c, d;
  cin >> a;
  cin >> b;
  cin >> c;
  cin >> d;

  cout << endl << smallest_of_four(a,b,c,d)<< endl;

  return 0;
}

 

Exercise 6:

A function that returns a value belonging to a given position of the Fibonacci serie. The challenge is to calculate the values, but I only needed a vector whose size is equal to the position that were given. Then I asigned the first two values, which are 0 and 1 respectively, and with a for, I added the two past numbers related with the number now being calculated, until the counter is equal to the requested position.

#include <iostream>
using namespace std;

unsigned long int fibonacci(int n)
{
  unsigned long int F[n];
  F[0]=0;
  F[1]=1;
  for (int c=2; c<=n; c++)
  {
    F[c]=F[c-1]+F[c-2];
  }
  return F[n];
}

int main()
{
  int n;
  cin >> n;
  cout << fibonacci(n) << endl;

  return 0;
}

 

Exercise 7:

A function that receives a list of numbers and returns the sum of their squares. I used a for and the function pow of the library <math.h>

#include <iostream>
#include <math.h>
using namespace std;

double sumsquares_list(double list[], int N)
{
  double Sum=0;
  for (int c=0; c<N; c++)
    Sum+=pow(list[c],2);

  return Sum;
}

int main()
{
  int N;
  cout << "Cantidad de valores: ";
  cin >> N;
  double list[N];
  for (int c=0; c<N; c++)
  {
    cout << "Valor " << c+1 <<": ";
    cin >> list[c];
  }

  cout << "\n\nLa suma de los cuadrados de esos números es igual a " << sumsquares_list(list,N) << endl;

  return 0;
}

 

Exercise 8:

A program that calculates the square root through the Babylonian Method.

#include <iostream>
using namespace std;

long double square_root(long double N)
{
  long double y=1, c;
  for(int i=0; i<1000; i++)
  {
    c=N/y;
    y=(y+c)/2;
  }
  return y;
}

int main()
{
  int N;
  cout << "Square Root... \n\nNumber: ";
  cin >> N;
  cout << "The square root of "<< N << " is equal to "<<square_root(N) << endl << endl;
  return 0;
}

 

Exercise 9:

A function that find the number of times that the word “banana” appears in a text file.

#include <iostream>
#include <ctype.h>
using namespace std;
#include <fstream>

bool compare(char vector_prueba[], int N=6)
{
  char BANANA[6]={'b','a','n','a','n','a'};
  bool result=true;
  int c=0;
  while(c<6)
  {
    if (BANANA[c]==vector_prueba[c]) c++;
    else return false;
  }
  return true;
}

int find_Bananas(string nombre)
{
    fstream ficheroEntrada;
    int Ban=0;
    char letra;

    ficheroEntrada.open ( nombre.c_str() , ios::in);
    if (ficheroEntrada.is_open()) {

        while (! ficheroEntrada.eof() ) {
          ficheroEntrada >> letra;
          letra = tolower(letra);
          if (letra == 'b')
          {
            char bananatest[6]={'b'};
            for(int i=1; i<6; i++)
            {
              ficheroEntrada >> letra;
              bananatest[i] = letra;
              bananatest[i] = tolower(bananatest[i]);
            }
          if (! ficheroEntrada.eof() ){
             if (compare(bananatest,6)) Ban++;
           }
         }
        }

        ficheroEntrada.close();
    }
    else cout << "Fichero inexistente o faltan permisos para abrirlo" << endl;
    return Ban;
}
int main()
{
    string nombre;
    cout << "\n\nDime el nombre del fichero: ";
    getline(cin,nombre);
    cout << "\nThere is/are " << find_Bananas(nombre) << " banana's in the file.\n\n" << endl;

    return 0;
}

 

Exercise 10:

A function that receives two positive integers and returns the greatest
common divisor of them. I determined which of the two values is the biggest and then I substract unit per unit until I find a value that can divide both numbers and give as a result integers. I made this with some conditionals and a while loop.
#include <iostream>
using namespace std;

int gcd(int X, int Y)
{
  int D;

  if(X>=Y)
    D=X;
  else
    D=Y;

  while ((X%D)!=0 || (Y%D)!=0)
    {D--;}

  return D;
}

int main()
{
  int X,Y;
  cin >> X;
  cin >> Y;
  cout << gcd(X,Y) << endl;
  return 0;
}

Quiz Week 9: The distance between coordinates

The task for today was only creating a function that could calculate the distance between two pair of coordinates on the cartesian coordinates plane that were given for the user. In the quiz was not necessary to create the entire program, but the function cause it was the only part required.

To make this part of the code, I utilized the Pythagoras Theorem cause if we conect the points given, we form a right triangle, of which we know its opposite and adjacent sides, and therefore we can calculate its hypotenuse. But for doing this we have to make a substraction between “x” points and then “y” points, so we have the exactly mesures. Then we apply the Pythagoras Theorem. And that’s all.

This is my resulting function:

float distance(float x1, float y1, float x2, float y2)
{
  float D;
  D= sqrt(pow((x2-x1),2) + pow((y2-y1),2));

  return D;
}

 

Homework 9: Multipart data and files

In this asingment we are going to read a text file and count the number of both lines and characters present on the document.

We need to use the libraries #include and #include to be able to use the functions that open and read text documents.

This is my code.

#include 
#include 
using namespace std;

int main()
{
  fstream text1;
  int lines=0, chars=0; // we initialize two variables for lines and characters, to count them
  string line; //we declare and string variable to read a line
  char letter; // this is gonna let us read each character

  text1.open("Archivo.txt", ios::in); // the file is open
  while(! text1.eof()) // reads each line and counts it
  {
    getline(text1,line);
    lines++;
  }
  text1.close();
  fstream text2;
  text2.open("Archivo.txt", ios::in); // the file is open
  while (! text2.eof() ) { // reads each character and counts it. 
    text2 >> letter;
    chars++;
  }
  text2.close(); // close the file
  lines-=1;
  chars-=1;

  cout << "\nThe file contains ... \n" << endl;
  cout <<"Amount of lines: " << lines << endl;
  cout <<"Amount of characters: "<< chars << endl << endl;



  return 0;
}

Quiz Week 8

This class we were oredered to write a code that generates the Fibonacci series. I was a really challenging task, ’cause my logic didn’t adapted to the situation righly.

Finally I used some loops, vectors and a function to make it work. This is what I wrote.

#include <iostream>
using namespace std;

int fibonacci(int n)
{
  int sum[n];
  sum [0]=0;
  sum [1]=1;
  for(int c=2 ; c<=n ; c++)
    {
      sum[c]=sum[c-1]+sum[c-2];
    }
  return sum[n];
}

int main()
{
  int n;
  cout << "Introduce the last number position of the series: ";
  cin >> n;
  int sum[n];
  for(int c=0 ; c<=n ; c++)
  {
    sum[c] = fibonacci(c);
  }

  for(int c=0 ; c<=n ; c++)
  {
    if (sum[c]==sum[n])
      cout << sum[c];
    else
      cout << sum[c] << ", ";
  }
  cout << endl;
  return 0;
}

Actually, this code is not so complicated to do, you just need to see it in a different way, thinking how to explain to a computer that it is required to sum the two numbers before to obatain the third value.

Now, I have to change loops for recursions, but since I need to do other things, I will let it for the weekend. Meanwhile, do you want to try it?

Homework 8: Yo soy 196

We are going to calculate the quantity of Lychrel numbers (natural numbers that doesn’t convert on palindromes after a serie of aditions, for example, 196 is a Lychrel number), natural and made palindromes that are present in a range of integer numbers given by the user.

If we want to convert a non-natural palindrome to a palindrome we have to sum its reverse until we obtain the palindrome.

Using this logic, we can declare some variables that acumulate the reverse and suspect numbers, and evaluate a significant number of times until either do we find the palindrome or do we determine that the given number is Lychrel.

To make all this process I utilized some while loops where I flip the numer and then compare the resulting number with the original one.

You can see my code here…

// El programa usa Big Integer para almacenar más datos. Esta es una librería creada por el maestro.
#include <iostream>
//#include <math.h>
#include <string>
#include "BigIntegerLibrary.hh"
using namespace std;

BigInteger reverse(BigInteger N)
{
  BigInteger M=0, n=N;
  int d=0;

  while(n!=0)
  {
    d++;
    n/=10;
  }

  for (;d>0; d--)
  {
    BigInteger D=1;
    for(int c=0; c<d-1; c++)
      {D*=10;}
    M+=(N%10)*D;
    N/=10;
  }
  return M;
}

int main()
{
  BigInteger n, N, NatPal=0, MadePal=0, Lych=0, m, l;
  string s, S;

cout << "\nLower bound of the sequence: ";
  cin >> s;
  cout << "Upper bound of the sequence: ";
  cin >> S;
  n = stringToBigInteger(s);
  l = n;
  N = stringToBigInteger(S);

  for (; n<=N ; n++)
  {
    BigInteger c=0;
    m=n;
    if (n == reverse(n))
    {NatPal++;}
    else
    {
      do {
        m+=reverse(m);
        c++;
      } while(m!=reverse(m) && c!=30);

      if (c==30)
      {Lych++;}
      else
      {MadePal++;}
    }
  }

  cout << "\nWe are calculating how many natural and made palindromes, as well as Lycherel numbers, there are in the range given...\n\n"<< endl;
  cout << "The results for the range "<< l << " to " << N << " are:\n"<< endl;
  cout << "Natural palindromes: " << NatPal << endl;
  cout << "Made palindromes (Non-Lycherel numbers): " << MadePal << endl;
  cout << "Lycherel candidates: " << Lych << "\n\n";
  return 0;
}