What is the most efficient way to find GCD of two integers

Tags

, , , , ,

We know that in Mathematics, the greatest common divisor or GCD of two or more integers (provided they are not zero), is the largest positive integer that can divide each of the integers.

There might be many other positive integers that can divide the two numbers, however, the GCD will always be the largest among them. After the GCD there will not be any integer left that can divide the two integers.

You have heard of Euclidean Algorithm, that uses division method. But there are a few more, and they might look interesting to you.
package fun.sanjibsinha.gcd;

public class FindGCD {

static int numOne = 0;
static int numTwo = 0;
static int remain = 0;

static int divisionBased(int num1, int num2){
int temp;
while (num2 != 0){
temp = num2;
num2 = num1 % num2;
num1 = temp;
}
return num1;
}

//this is Euclid's original version
static int subtractionBased(int num1, int num2){
int temp;
while (num1 != num2){
if(num1 > num2)
num1 = num1 - num2;
else
num2 = num2 - num1;
}
return num1;
}

static int recursiveBased(int num1, int num2){
if(num2 == 0){
return num1;
} else {
int temp;
temp = num1 % num2;
return recursiveBased(num2, temp);
}
}

public static void main(String[] args) throws ArithmeticException {

System.out.println(recursiveBased(1071, 462));
//output 21

}
}

Call by value and Call by Reference in Java

Tags

, ,

I would like to give you an example first. After that, I will explain what happens inside.

Let’s start with a Child class which has a field called ‘height’.

Child class:

package fun.sanjibsinha.classesandobjects;

public class Child extends Parent {
    public int height;
}

Now the main method:

package fun.sanjibsinha.classesandobjects;

public class Main {
static void passPrimitive(int y){
//invoking this method with a local variable
//cal this method with its own value
y = 11;
System.out.println("Value of y : " + y);
}
static void passingObject(Child child){
//invoking this method with a new instance
//always references to this object
// and reflects this value
child.height = 10;
System.out.println("Height of child object: " + child.height);
}

public static void main(String[] args) {
//call by value
int x = 2;
passPrimitive(x);
System.out.println("Value of x : " + x);
System.out.println();
Child childOne = new Child();
childOne.height = 100;
System.out.println("Height of childOne : " + childOne.height);
//call by reference
passingObject(childOne);
System.out.println("Height of childOne now refers to the previous child object : "
+ childOne.height);
}

}

Let us first see the output first:

Value of y : 11
Value of x : 2

Height of childOne : 100
Height of child object: 10
Height of childOne now refers to the previous child object : 10

In the above section of code, the primitive data type ‘int’ has been passed into methods as a primitive argument, as well as a value.

Any changes to the value of the parameters only exist in the method scope. When the method returns, any changes made to the parameters are lost instantly. Here exactly that happens. We made changes to the value of the parameter of the method ‘passPrimitive(int y)’; and, the method returns the value of ‘y’, but that does not affect the value of ‘x’.

In case of the objects, since the reference variable points the HEAP memory. The exactly opposite happens. The newly created reference type variable points to the previously created object and reflects its value. The changes made to the parameters are not lost.

Dependency Injection in C#

Tags

, ,

It is rather a translation of my previous Java post that I had posted on 26th of December.

I just translated the Java version into the C#; nothing else. For that reason, I am not going to elaborate the explanation part. If you want to know how it works, please read the previous post’s theory part.

Here I am sharing only the code that I have written in Visual Studio in Ubuntu.

First the Mobile.cs:

using System;
class Mobile {
IConnection connect;
public void getConnected(IConnection connection){
this.connect = connection; connection.setConnection(true);
if(connection.getConnection()){
Console.WriteLine("Connected through " + Cable.name);
}
}
}

The next part will show you how I need a connection Interface.

Continue reading

Dependency Injection in Java

Tags

, , , ,

When an object depends on other objects for getting some utilities, it’s called dependency.

A mobile is dependent on WiFi object to get connected to web. Not only on WiFi alone, it might have dependency on Cable and Hotspot objects, for the same reason.

The question is how we can resolve this dependency?

We can always hard code it. It is allowed. However, in that case, the two objects are tightly coupled and each time you have to change the source code to change the dependency.

The solution is common interface. We can have a common connection interface so that we can change the interface if needed without disturbing the main Mobile class. If WiFi does not work, we can try Cable, if the Cable does not work, we can have another option left: Hotspot.

Let us see how we can do that in Java.

The Mobile class:

package fun.sanjibsinha.dependency;

public class Mobile {

private ConnectionInterface connect;

public Mobile(ConnectionInterface connect){
this.connect = connect;
}

public void getConneceted(){
System.out.println("The mobile is connected through " + connect.getName());
}

}

Continue reading

Introduction to Collections: Arrays are Lists in Dart

Tags

, , , , , , , , , , , , , , ,

laern-dart-the-hard-way

Learn Dart the Hard Way

This is the most common collection in every programming language: array or an “ordered group of objects”. In Dart, arrays are List objects. We will address them as ‘lists’ in our future discussion.
JavaScript array literals look like Dart lists. Here is a sample code we may consider to understand why this concept is important:

//code 2.14
main(List arguments) {
List fruitCollection = ['Mango', 'Apple', 'Jack fruit'];
print(fruitCollection[0]);
}

Consider another piece of code:

//code 2.15
main(List arguments) {
List fruitCollection = ['Mango', 'Apple', 'Jack fruit'];
var myIntegers = [1, 2, 3];
print(myIntegers[2]);
print(fruitCollection[0]);
}

What is the difference between these two code snippets? In the above code 2.14, we have explicitly mentioned that we are going to declare a collection of fruits. And we can pick any item from that collection from the key.

As we know, when in an array key is not mentioned with the value pair, it automatically infers that the key starts from 0. Therefore, the output of code 2.14 is ‘Mango’. In the second instance, Continue reading

Anonymous Functions: Lambda, Higher Order Functions, and Lexical Closures

Tags

, , , , , , , , , ,

laern-dart-the-hard-way

Learn Dart the Hard Way

Lambda, Higher-Order functions, and Lexical Closures have some similarities. In their namelessness and anonymity, these features of Dart are very interesting. Let us start with Lambda. Then we will discuss Higher-Order Functions and Closures. In reality, you will find that Lambda actually implements Higher-Order Functions.
Today I am going to talk about the Lambda only.
Next day, I will write about the other anonymous functions.
Continue reading

Python 3: Reusing With Regular Expressions

Tags

, ,

learn python the simple way

learn python the simple way

Get the book: Learn Python 3 the simple way

You have already seen how we can search and replace words in a file with the help of regular expression. Now we will try to reuse the code so that we can use them again and again. Besides, we will also try to write them in a more human readable way.
Let us first write the steps. What we want to achieve is very important before achieving something. Let us have a clear idea first and the best way is writing them down.
Continue reading

Static Variables and Methods in Dart

Tags

, , , , ,

Learn Dart the Hard Way

To implement class-wide variables and methods, we use the static keyword. Static variables are also called class variables. Let us first see a code snippet and after that, we will discuss the advantages and disadvantages of static variables and methods.

//code 7.1
// static variables and methods consume less memory
// they are lazily initialized
class Circle{
static const pi = 3.14;
static Function drawACircle(){
//from static method you cannot call a normal function
print(pi);
}
Function aNonStaticFunction(){
//from a normal function ou can call a static meethod
Circle.drawACircle();
print("This is normal function.");
}
}
main(List arguments){
var circle = Circle();
circle.aNonStaticFunction();
Circle.drawACircle();
}

And here is the output:

3.14
This is normal function.
3.14

As you see, static variables are useful for class-wide state and constants. So in the main() method we can add this line at the end:

main(List arguments){
var circle = Circle();
circle.aNonStaticFunction();
Circle.drawACircle();
print(Circle.pi);
}

And get the value of constant ‘pi’ again. Here, ‘Circle.pi’ is the class variable. And the class method is: ‘Circle.drawACircle();’. The biggest advantage of using static variables and methods is it consumes less memory. An instance variable once instantiated, consumes memory whether it is being used or not. The static variables and methods are not initialized until they are used in the program. It consumes memory when they are used.

A few things to remember:

1. From a normal function, you can call a static method.
2. From a static method, you cannot call a normal function.
3. In a static method, you cannot use the ‘this’ keyword. It is because the static methods do not operate on an instance and thus do not have access to this.

So, in the end, we can conclude that using static variables and methods depend on the context and situations. In the next part of the book, where we will build native iOS and Android mobile apps with the help of Flutter framework, you will see how and when we use static variables and methods.

Why we need Constructor in Dart

Tags

, , , , , , , ,

Learn Dart the Hard Way

The first and foremost task of constructors is the construction of objects. Whenever we try to create an object and write this line:
var fatherBear = Bear();
We actually try to arrange a spot in the memory for that object. The real work begins when we connect that spot with class properties and methods.
Using ‘constructor’ we can do that job more efficiently. Not only that, Dart allows to create more than one ‘constructor’, which is a great advantage.
Let us write our ‘Bear’ class in a new way of using constructor:

//code 3.10
class Bear {
int numberOfFish;
int hourOfSleep;
int weightGain;
Bear(this.numberOfFish, this.hourOfSleep);
int eatFish(int numberOfFish) => numberOfFish;
int sleepAfterEatingFish(int hourOfSleep) => hourOfSleep;
int weightGaining(int weightGain) => weightGain = numberOfFish * hourOfSleep;
}
main(List arguments){
var fatherBear = Bear(6, 10);
fatherBear.weightGain = fatherBear.numberOfFish * fatherBear.hourOfSleep;
print("Father bear eats ${fatherBear.eatFish(fatherBear.numberOfFish)} fishes. And he sleeps for ${fatherBear.sleepAfterEatingFish(fatherBear.hourOfSleep)} hours.");
print("Father bear has gained ${fatherBear.weightGaining(fatherBear.weightGain)} pounds of weight.");
}

Creating ‘constructor’ is extremely easy. Watch this line:

Bear(this.numberOfFish, this.hourOfSleep);

The same class name works as a function or method and we have passed two arguments through that method. Once we get those values, we would calculate the third variable. Writing constructor this way is known as “Syntactic Sugar”. In the later section of the book we will know more about the constructor.
Now it gets easier to pass the two values while creating the object. We could have done the same by creating constructor this way, which is more traditional:

//code 3.11
class Bear {
int numberOfFish;
int hourOfSleep;
int weightGain;
Bear(int numOfFish, int hourOfSleep){
this.numberOfFish = numOfFish;
this.hourOfSleep = hourOfSleep;
}
//Bear(this.numberOfFish, this.hourOfSleep);
int eatFish(int numberOfFish) => numberOfFish;
int sleepAfterEatingFish(int hourOfSleep) => hourOfSleep;
int weightGaining(int weightGain) => weightGain = numberOfFish * hourOfSleep;
}
main(List arguments){
var fatherBear = Bear(6, 10);
fatherBear.weightGain = fatherBear.numberOfFish * fatherBear.hourOfSleep;
print("Father bear eats ${fatherBear.eatFish(fatherBear.numberOfFish)} fishes. And he sleeps for ${fatherBear.sleepAfterEatingFish(fatherBear.hourOfSleep)} hours.");
print("Father bear has gained ${fatherBear.weightGaining(fatherBear.weightGain)} pounds of weight.");
}

In both cases, the output is same as before:

//output of code 3.11
Father bear eats 6 fishes. And he sleeps for 10 hours.
Father bear has gained 60 pounds of weight.

In the above code, you can even get the object’s type very easily. We can change the type of value quite easily. Watch the main() function again:

//code 3.12
main(List arguments){
var fatherBear = Bear(6, 10);
fatherBear.weightGain = fatherBear.numberOfFish * fatherBear.hourOfSleep;
print("Father bear eats ${fatherBear.eatFish(fatherBear.numberOfFish)} fishes. And he sleeps for ${fatherBear.sleepAfterEatingFish(fatherBear.hourOfSleep)} hours.");
print("Father bear has gained ${fatherBear.weightGaining(fatherBear.weightGain)} pounds of weight.");
print("The type of the object : ${fatherBear.weightGain.runtimeType}");
String weightGained = fatherBear.weightGain.toString();
print("The type of the same object has changed to : ${weightGained.runtimeType}");
}

And here is the output:

//output of code 3.12
Father bear eats 6 fishes. And he sleeps for 10 hours.
Father bear has gained 60 pounds of weight.
The type of the object : int
The type of the same object has changed to : String

How Functions or Methods Work in Dart

Tags

, , ,

How Functions or Methods Work in Dart? Here is a quick tip that can teach you the basic programming knowledge of Dart.

Learn Dart the Hard Way

We need to understand a few important features of functions before we dig deep into object-oriented programming again. The proper understanding of functions will help us to understand methods inside a class.
First of all, there are functions that just do nothing.
It called: ‘void’.
Let us consider this code:

//code 3.15
main(List arguments){
print(showConnection());
}
//optional positional parameter
String myConnection(String dbName, String hostname, String username, [String optionalPassword]){
if(optionalPassword == null){
return "${dbName}, ${hostname}, $username";
} else return "${dbName}, ${hostname}, $username, $optionalPassword";
}
void showConnection(){
myConnection("MySQL", "localhost", "root", "*******");
}

We have declared the function ‘showConnection()’ as ‘void’ and want to return it through the ‘main()’ function. We have this output:

//output of code 3.15
bin/main.dart:4:9: Error: This expression has type ‘void’ and can’t be used.
print(showConnection());

We cannot use the type ‘void’. If we use, we cannot return something through that function. So from a function we always expect something. We want a function to return a value.
So we are going to change the above code and write it this way:

//code 3.16
main(List arguments){
var myConnect = myConnection(“MySQL”, “localhost”, “root”, “*******”);
print(myConnect);
}
//optional positional parameter
String myConnection(String dbName, String hostname, String username, [String optionalPassword]){
if(optionalPassword == null){
return “${dbName}, ${hostname}, $username”;
} else return “${dbName}, ${hostname}, $username, $optionalPassword”;
}

A simple program to express the database connections parameters. In the above code, we have used a new concept called the optional parameter. You have already known that if we declare parameters or arguments in our functions, we have to pass them as it is. Otherwise, it gives us errors. However, we can use the concept of ‘optional parameters’. In the function ‘myConnections()’ we have passed four arguments.

Watch this line:

String myConnection(String dbName, String hostname, String username, [String optionalPassword]){}

We have written the last argument as [String optionalPassword]. It means this argument is optional. You do not have to pass it when you call the function. Here the logic is simple. If the optional parameter ‘optionalPassword’ is not defined when we pass it inside the ‘main()’ function, it is treated as ‘null’. Since it has been defined and passed it afterward, it is not null. Therefore, we have got this output:

//output of code 3.16
MySQL, localhost, root, *******

Now, we change the above code slightly and will not pass that argument anymore.
//code 3.17
main(List arguments){
var myConnect = myConnection("MySQL", "localhost", "root");
print(myConnect);
}
//optional positional parameter
String myConnection(String dbName, String hostname, String username, [String optionalPassword]){
if(optionalPassword == null){
return "${dbName}, ${hostname}, $username";
} else return "${dbName}, ${hostname}, $username, $optionalPassword";
}
The output also changes:
//output of code 3.17
MySQL, localhost, root

Compare these two lines before and after and we will only then understand why optional parameter is important:

//code 3.16
var myConnect = myConnection("MySQL", "localhost", "root", "*******");
//code 3.17
var myConnect = myConnection("MySQL", "localhost", "root");

If we did not declare it as optional, it would have given us an error. Let us change the optional parameter and see what type of error we get.

//code 3.18
main(List arguments){
var myConnect = myConnection("MySQL", "localhost", "root");
print(myConnect);
}
//optional positional parameter is no more
String myConnection(String dbName, String hostname, String username, String optionalPassword){
if(optionalPassword == null){
return "${dbName}, ${hostname}, $username";
} else return "${dbName}, ${hostname}, $username, $optionalPassword";
}
Now optional parameter is no more, and for that reason, we encounter this error in the output:
//output of code 3.18
bin/main.dart:3:31: Error: Too few positional arguments: 4 required, 3 given.
var myConnect = myConnection("MySQL", "localhost", "root");
^
bin/main.dart:8:8: Context: Found this candidate, but the arguments don't match.
String myConnection(String dbName, String hostname, String username, String optionalPassword){

Since there was no optional parameter we had to pass the fourth argument. In the previous code snippets, we did not have to do that.
Since in Dart, a function is an object, the same concept is true in case of methods and you will find it when we will discuss object-oriented programming again.