Power function

In C/C++ (and also other languages), we have the built in power function to raise a number to a given power. What if we need to calculate the power of a number to 100, like \(2^{100}\)? This is often the case in competitive programming. Maybe we'll run a loop 100 times and calculate it, but this is so inefficient. So, we need to find a power function which can calculate the power to a given number really fast.

Let's consider the expression \(2^{100}\). We can rewrite this to \((2^{50})^{2}\) and the result will not change. Now, we have a smaller power to calculate, right? We can again, rewrite the previous expression to \(((2^{25})^{2})^{2}\). Note that, it was possible to rewrite the expression by halving the power inside the parenthesis only because the power was even. If we were try and rewrite an odd power, it wouldn't be possible. We cannot divide an odd number to half evenly (e.g 25 cannot be divided by 2 evenly). What can we do then? We can just multiply the number itself to balance the power (increase the power by one, to make it odd). Let's rewrite the last expression:
$$
((2^{24+1}))^{2})^{2}
\\ = ((2*2^{24}))^{2})^{2}
\\ = ((2*(2^{12})^{2})^{2})^{2}
$$ The result is still the same. We can go on like this until the power becomes zero. We can see that this pattern keeps repeating and after each step, its calculating a smaller state, its a recursive problem! Here's a picture taken from http://www.shafaetsplanet.com/planetcoding/?p=936 demonstrating the recurring steps.

Implementation in code:
int POW(int x, int p) {
   // x^0 = 1 where x is any number
   if (p == 0) return 1;
   
   // if the power is not even, then multiply the number
   // itself to balance it as stated in the post
   if (p % 2 != 0) {
    int n = POW(x, p/2);
    return x * n * n;
   } else {
    int n = POW(x, p/2);
    return n * n;
   }
}

LightOJ 1000 - Greetings from LightOJ

In this problem, we're asked to just add two input numbers and print them out accordingly. Here's the code.


#include <bits/stdc++.h>
using namespace std;

int main() {
  int T, i=1;
  scanf("%d", &T);
  while (T-- > 0) {
    int a, b;
    scanf("%d %d", &a, &b);
    printf("Case %d: %d\n", i++, a+b);
  }
  
  return 0;
}

Enabling gzip compression in django

GZip compression allows the server to compress data before it is sent (on the fly) and the upon arrival of the data on client side, the browser does the unzipping/decompression of the data and shows it to the user. Enabling gzip compression can help you save about 50% plus bandwidth, thus not only making your site more responsive, but also saving huge amount of cost. Here's how you enable gzip compression in Django:

Open your settings.py file and find the MIDDLEWARE_CLASSES tuple. Add the following at the top:

MIDDLEWARE_CLASSES = (
    'django.middleware.gzip.GZipMiddleware',
    # ...
)

And, that's it! You can also enable gzip compression from your Apache, Ngingx and other servers too, look up their documentation.

Constructors in C++

A constructor, as its name implies, is used to create (construct) objects. It's like any another function but with exceptions -
A constructor is always associated with a class and this function does not return anything and thus it does not have any return type associated with it.
It is used only for aiding in creation of objects. Let's look at how a normal function looks:

// this function has a return type of 'int'
int add(int a, int b) {
 return a + b;
}

Name of the function is add, its return type is int (i.e it returns an integer after it is done with its operations) and it takes in two parameters - a and b.
Now, let's say we have a Box class and for creating a Box we need to follow some steps, we cannot just create one out of nothing. For example, we cannot create a Box without the required width and height obviously! Here's how a constructor for the Box class might look like:

class Box {
public:
 // Box is the name of the constructor function
 // ITS NAME IS ALWAYS THE SAME AS ITS CLASS NAME
 // Since, a constructor function does not return anything,
 // it does not have a return type before its name
 Box(int width, int height) {
  // this constructor takes width and height

  /*
  Possible steps to make a Box object

  1.  Get a cardboard
  2.  Get the desired width and height
  3.  Make (construct) the box by
   cutting the cardboard according to width/height
  */
 }
};

Here, we defined a constructor for the Box class. Notice, the name of the constructor function is the same its class name and that it has no return type. Let's complete the definition of our class and use it in code.

#include <iostream>
using namespace std;

class Box {
 int box_width;
 int box_height;

public:
 // Box is the name of the constructor function
 // ITS NAME IS ALWAYS THE SAME AS ITS CLASS NAME
 // Since, a constructor function does not return anything,
 // it does not have a return type before its name
 Box(int width, int height) {
  // this constructor takes width and height

  /*
  Possible steps to make a Box object

  1.  Get a cardboard
  2.  Get the desired width and height
  3.  Make (construct) the box by
   cutting the cardboard according to width/height
  */

  box_width = width;
  box_height = height;

  cout << "Making a new box..." << endl;
  cout << "Gathering some cardboard..." << endl;
  cout << "Width: " << box_width << endl << "Height: " << box_height << endl;
  cout << "Making the box with the given width and height..." << endl;
  cout << "Done! Enjoy your new box" << endl;
 }
};

int main() {
 // Create a Box object named b
 Box b(30, 20);

 return 0;
}

Now, run this program yourself and enjoy making new boxes!

Classes and Objects in C++ and real life

Class. Object. They are used frequently in the land of object oriented programming (OOP). Classes and objects are nothing mysterious. Look around you, there are so many objects - table, chair, mobile, TV, fridge, etc. All of these are real life objects.

Manufacturers use blueprints to create these objects. The blueprints define how every object of a particular type of product (say iPhone 7) will look like and how they'll behave. Since, all the iPhone 7 objects are created from a single iPhone 7 blueprint, they all look and behave the same, for example - they all have a camera at the back, they can make calls, etc. In our OOP land, these blueprints are known as Class. A class defines how an object will be created, the properties it'll have and the actions that can be performed on that object.

Now let's observe an object. Each object has its own properties, for example, think of your mobile phone - it has properties like "the phone is switched on/off", "the phone's brightness level is set to 5", "the phone is in vibration mode" and so on. Apart from the properties that your mobile has, you can also do stuffs (perform some action) with it - "switch on/off the phone", "increase brightness level", "make a call", "text to someone", etc. This is exactly what an object in OOP is. An object has properties and functions/methods (which perform an action).

Now that we know what an object and a class is, let's see how they're defined in code by creating a Mobile class:

#include <iostream>
using namespace std;

class Mobile {
 // name of the mobile
 string mobile_name;
 // volume level of the mobile
 int volume_level;
 // brightness level of the mobile
 int brightness_level;
 // by default the phone is off
 bool phone_is_on = false;
};

We defined a Mobile blueprint (class) which has properties - mobile_name, volume_level, brightness_level and phone_is_on (which denotes the phone is either on/off). Now, let's define some actions for the Mobile class.

class Mobile {
 // name of the mobile
 string mobile_name;
 // volume level of the mobile
 int volume_level;
 // brightness level of the mobile
 int brightness_level;
 // by default the phone is off
 bool phone_is_on = false;

public:
 void toggle_phone_state() {
  if (phone_is_on == false) {
   cout << "Phone is switched on." << endl;
   phone_is_on = true;
  } else {
   cout << "Phone is switched off." << endl;
   phone_is_on = false;
  }
 }

 void set_volume(int vol) {
  volume_level = vol;
 }

 void set_brightness(int brightness) {
  brightness_level = brightness;
 }
};

Now, we have defined actions for the class. Notice, how actions (methods/member functions) are just plain ordinary functions. Let's use this blueprint (class) to create an object.

#include <iostream>
using namespace std;

class Mobile {
 // name of the mobile
 string mobile_name;
 // volume level of the mobile
 int volume_level;
 // brightness level of the mobile
 int brightness_level;
 // by default the phone is off
 bool phone_is_on = false;

public:
 void toggle_phone_state() {
  if (phone_is_on == false) {
   cout << "Phone is switched on." << endl;
   phone_is_on = true;
  } else {
   cout << "Phone is switched off." << endl;
   phone_is_on = false;
  }
 }

 void set_volume(int vol) {
  cout << "New volume is: " << vol << endl;
  volume_level = vol;
 }

 void set_brightness(int brightness) {
  cout << "New brightness is: " << brightness << endl;
  brightness_level = brightness;
 }
};

int main() {
 // Create an object of class Mobile named - my_android
 Mobile my_android;
 // perform actions on the my_android object by using a dot and the action name
 // my_android . action_name();
 my_android.toggle_phone_state();
 my_android.set_volume(5);
 my_android.set_brightness(3);

 return 0;
}

NOTE: You may have noticed a public keyword. Its okay to not understand it for now, just write it as it is.
Now, you can create as many Mobiles as you want. Go and run the program!

Function overloading in C++: Basic

Function overloading is an interesting concept and its very useful in some scenarios. So, what is function overloading? Function overloading means defining multiple functions with the same name which differ in either their parameter numbers, parameter types or both. Let's see an example to clear things out:
Let's say we want to define an add function. Depending on the type of its parameters, it'll return different values. For example, when you pass two integers 5 and 3 it'll return 8. When you pass 5.05 and 2.90 it'll return 7.95, when you pass two strings - "hello " and "world" it'll concatenate (join) them together and return "hello world". Here's how we do can do it -

#include <iostream>
using namespace std;

// add two 'int' and return their sum
int add(int a, int b) {
 return a + b;
}

// add two 'double' and return their sum
double add(double a, double b) {
 return a + b;
}

// concatenate (join) two 'string' and return the result
string add(string a, string b) {
 return a + b;
}

// this function just adds 5 to any number it is supplied
int add(int x) {
 return x + 5;
}

int main() {
 // this add(5, 3) will call the function at line 5
 cout << add(5, 3) << endl;

 // this add(5.05, 2.90) will call the function at line 10
 cout << add(5.05, 2.90) << endl;

 // this add("hello ", "world") will call the function at line 15
 cout << add("hello ", "world") << endl;

 // this add(10) will call the funciton at line 20
 cout << add(10) << endl;number

 return 0;
}

The output will be:

8
7.95
hello world
15

As you can see, depending on the type and/or number of arguments supplied, the compiler is smart enough to call the correct function.
Function overloading is also possible in the context of a class. You can have multiple overloaded functions as members of the same class. Not only that, even constructors can be overridden.

NOTE: Return type of a function is never taken into consideration in case of function overloading. Always keep that in mind.

Default parameters in C++

In C++, you can define a default value for parameter(s) of a function. Here's how you do it:

#include <iostream>
using namespace std;

void show_info(string name = "Pantha", int age = 20) {
 cout << name << " is " << age << " years old." << endl;
}

int main() {
 show_info();
 show_info("Beck");
 show_info("Tony", 22);

 return 0;
}

Here, we have defined a function named show_info which takes two arguments - name and age. We also set a default value for name = "Pantha" (which is of type string) and also, the default value for age = 20. Then we call the function show_info three times - three different ways (in this case). Its as easy as that!
One more thing that you should be aware of is, you cannot change the position of arguments while calling the function. For example, you CANNOT DO the following:

show_info(20, "Andy");

That's all!

Power function

In C/C++ (and also other languages), we have the built in power function to raise a number to a given power. What if we need to calculate ...