Vedic Math - Cube Roots of more than 6-Digit Number - Part I

Back after a long break. In previous article, we learn how to find the cube root of 4 or 5 or 6 digits perfect cubes. Let us continue it further and discuss how to find the cube root of perfect or imperfect cubes.

In this article, we shall learn to find the cube roots for:
1. Cube root of perfect cubes, for any number of digits.
2. Cube root for all the cubes, whether perfect cubes or not.

To summarize what we have learned till now for cube root:

Arrange the given number in three-digit groups, starting from right to left. A single digit, if any left over at the left hand side, is counted as a simple group itself. The number of  digits in the cube root will be the same as the number of digit-groups  in the given  number itself.

  • 169 will count as 1 group 
  • 1 258 will count as 2 groups 
  • 43 781 will count as 2 groups
  • 2 154 890 will count as 3 groups

If the given number has 'n' digits, its cube root will be having n/3 or (n+1)/3 digits. Also remember few other points from previous article:

The Cubes  of the first nine natural numbers    
1³ = 1        2³ = 8        3³ =27        4³ = 64        5³ = 125        6³ = 216        7³ = 343        8³ = 512         9³ = 729        10³ = 1000
From it, we understand that

  • 1,4,5,6,9,0 numbers repeat themselves in the ending of their cubes
  • 2,3,7 and 8 have their complements from 10, at the end of their cube

Let us start with actual technique now. Any number can be written in an algebraic expression. For example, if arithmetical number is 'dcba', it can be written in algebraic form as:
Algebraic Expression is: a + 10b + l00c + 1000d.

Now if we need to find the cube of a number 'cba', algebraically we can expand it like  (a+10b+102c)3. Let us expand it:
(a+10b+102c) 3 =  a3 + 10 (3a2b) + 102 (3ab2+3a2c) + 103 (b3+6abc) + 104 (3ac2+3b2c) + 105 (3bc2) + 106 (c3)

Now removing the powers of ten and putting the result in algebraic form, it tells us the formation of cube as:
(1) The units' place is determined by a³.
(2) The tens' place is contributed by 3 a2b
(3) The hundreds' place is contributed to by 3ab2 + 3a2c
(4) The thousands' place is formed by b³ + 6abc
(5) The ten thousands' place is given by 3ac2 + 3b2c
(6) The hundred thousands' (lakhs') place is constituted of 3bc2 ; and
(7) The millions' place is formed by c³.

The number of zeroes in the various coefficients of the expanded Algebraic Expression are the basis of the formula / analysis.

Case1 :  Cube root of perfect cubes for any number of digits

Suppose we have a cube number n of any number of digits. To find its cube root, find following:
- The number of groups (N) in cube (as we discussed above to make the sets of 3 digits)
- First digit of cube root denoted as 'F' (Nearest cube root of first group from left)
- Last digit of cube root denoted as 'L' (Cube root of last group from left)
- Middle numbers of cube root(i.e. 'M' or 'H' or 'J'....), we shall find using the procedure.

Following are the steps for the procedure:
(i) From the units' place of given number, subtract the L³ (i.e. a³, refer to algebraic expression above); and that eliminates the last digit of the number.
(ii) From the ten's place, we subtract 3L2M (i.e. 3a2b) and thus eliminate the second last digit (penultimate digit).
(iii) From the hundreds' place, we subtract 3LM2 + 3L2F (i.e. 3ab2 + 3a2c) and hence eliminate the pre-penultimate digit.
and so on

The Beautiful Mind

This is an incident from my childhood. In my school days, I used to wake up very early in the morning, early means 4 am. I learnt this habit from my mother and grandmother. At that time, I had a wish to surprise them by waking up earlier than them. However, challenge was, ‘How I can do it without alarm clock’. I kept on thinking this for many days, and this wish grew stronger in my mind. One day, to my surprise, I woke up earlier than them. This happened for next many next days. Eventually I realized that my strong wish actually made my sub-conscious mind to help me in waking me up at a specific time. Sub-conscious mind is capable to understand the time. Then I experimented by setting different times and that worked. I utilized this amazing power of mind many a times during my college days too.

This is the power of our sub-conscious mind. A small 3 pound organ, but having 1 trillion cells, and 100 billion neurons. It has 10 to the power 1 million ways of wiring itself and can store 1000 TB of information. I still have only 1 TB of external disk. Further, it can process 10 to the power 13 operations per second. Amazing speed. Slowest information speed in mind is around 260 mph, faster than most of the fast cars. We have this kind of powerful organ with us, which if utilized properly, can do amazing things. However, power is good as long as it is in control. Uncontrolled mind can also do ‘not so good’ things. How, let us understand with an example of Robot (equivalent to sub-conscious mind).

Suppose we have an intelligent, self-learner robot. It is being programmed to serve us. One of the important task assigned to it is, to defend us from all external threats and also to give us suggestion in case of any problem. It is doing its duty very well by taking a fight with attackers. Intensity of fight is specified by us.

Now visualize a scenario when this Robot become more intelligent with time. One day, it decides to teach the attacker a better lesson. So it ignores our instruction for intensity of fight, and instead of a simple slap, it breaks the hand of attacker. Although it is doing all that for you, but now it is acting in autonomous mode and hence can take decision which can create problem in real life. This is how our mind does many of the times. That’s why many a times, we overreact to situation, which is not good. Robot is good as long as it is in your control and following your instructions.

Spring RoutingDataSource to Work with Multiple DataSources - II

In previous article, we have discussed about using Spring 'AbstractRoutingDataSource' to dynamically routing the database call to desired database (i.e. data source). This is very handy feature and useful in various scenarios. 

One important use case can be in multi-tenant application. In multi-tenant application, one of the database design consideration can be to use separate database for each tenant. It helps to keep the data of each tenant separate, and would be good for performance also. And, good design would require to use the same application layer code to work with all tenant and their specific database. In this scenario, use of 'AbstractRoutingDataSource' can help to achieve these design considerations. Extend the AbstractRoutingDataSource to create a custom 'MultiTenantRoutingDataSource'. Use a thread local application context state holder to maintain the tenant state for current flow. Use this thread local context in extended 'MultiTenantRoutingDataSource' to return the tenant specific data source. Again keep in consideration please, that Routing Data Source will be invoked by TransactionManager before starting the transaction only. Once transaction is started, data source can not be changed. 

Let us see the example of data source definition in Context for dynamically switching between OLTP and Reporting Database: 

<bean id="dataSourceOltp" name="oltpDataSource" class="..PooledDataSource">
<property name="targetDataSource">
<jee:jndi-lookup jndi-name="jdbc/DB" cache="true" />
</property>
</bean>


<bean id="dataSourceReportDb" name="dataSourceReportDb" class="..PooledDataSource">
<property name="targetDataSource">
<jee:jndi-lookup jndi-name="jdbc/ReportDB" cache="true" />
</property>
</bean>

<bean id="customDataSource" class="com.a.b.common.db.DBCustomRoutingDataSource ">
<property name="targetDataSources">
<map key-type="com.a.b.util.DataSourceConstants">
<entry key="OLTP_DB" value-ref="dataSourceOltp"/>
<entry key="REPORT_DB" value-ref="dataSourceReportDb"/>
</map>
</property>
<property name="defaultTargetDataSource" ref="dataSourceOltp"/>
</bean>

<bean id="txAwareCustomDS" name="txAwareCustomDS" class="org.springframework.jdbc.datasource.Transac tionAwareDataSourceProxy">
<property name="targetDataSource" ref="customDataSource">
</property>
</bean>

<bean id="CustomTxManager" class="org.springframework.jdbc.datasource.DataSou rceTransactionManager">
<property name="dataSource" ref="txAwareCustomDS" />
</bean>


In above context definition, we may define data sources for multiple tenants in place of OLTP or Reporting Database. To extend the design further for multiple tenants, definition can be made dynamic.

Important Note:

If you are using TransactionAwareDataSourceProxy with DataSourceTransactionManager, it should always be the outer most wrapper in the hierarchy. Keep data sources hierarchy as following:

TransactionAwareDataSourceProxy > Routing Data Source > Lazy Data Source > Pooled Data Source

Reason is, DataSourceTransactionManager will never work with TransactionAwareDataSourceProxy, rather it picks the wrapped data source to work upon. DataSourceTransactionManager has special handling for TransactionAwareDataSourceProxy to work with actual DataSource wrapped in it. So it is important to keep the TransactionAwareDataSourceProxy as outer most layer. Or otherwise, DataSourceTransactionManager will not be able to handle the transactions properly. Read more at following links:

Java Technology Enthusiasts - How to set Transaction Manager Programatically
Spring Forum - Problem in Managing Managing Transaction with AbstractRoutingDataSource

------------------------------------------------------------------------------------------------------------
Hope it will help. Please share comments for addition. You may contribute by:
  • Posting your comments which will add value to the article contents
  • Posting the article link on Social Media using 'Social Media Bookmark' bar
  • Consider joining us at 'Java Technology Enthusiasts' linkedin group to participate in discussions
  • Connecting with 'VedantaTree' on Facebook

New Version 3.1 of ExpressionOasis Released

New version 3.1 of ExpressionOasis has been released.

Release Notes: 

  1. Grammar class is made configurable now. Developers can implement custom Grammar class and can specify this in configuration. ExpressionOasis will pick this at runtime. 
  2. Made grammar.xml path configurable by exporting it to config.xml
  3. Improved code of ExpressionFactory to improve the performance
  4. Defined new way to add function definition by providing new API in Grammar interface 
  5. Exposed Grammar through ExpressionEngine Class, so that user can get the metadata if required and also can add specific metadata like custom function identification etc
  6. Added three new String operation expressions > startsWith, endsWith, contains (Contribution by Girish Kumar) 
  7. Made config.xml path configurable from System Property (Contribution by Girish Kumar)
  8. Improved documentation
Download:
In case of any issue or any new requirement, please log it here. If you are extending the framework to add new features, please consider to contribute these back to the project. It will help everybody whosoever is using the ExpressionOasis.

Follow us:

Spring RoutingDataSource to Work with Multiple DataSources

Finally back to blogging. It was a long journey to get ready, pick the pen (i.e. computer) and start writing again. Writing is a matter of habit.

Today we are going to discuss about using multiple data sources with Spring Transaction Management. Scenario is,

  • Application is having lot of legacy code
  • Application needs to work with more than one databases
  • There are some legacy methods in application which are supposed to work with any one of the database depending upon use case. Same method could be invoked with different data source context for other transaction.
  • Application is using Spring Transaction Management
  • Requirement of Spring Transaction Management is to declare data sources and associated transaction manager with application context (1 to 1 relation)

What would be the initial design considerations. 
  • Define all required data sources in application context
  • Define corresponding transaction managers too
  • Use any of the Persistent Template to implement the DAOs.
  • Define desired transaction behavior on service methods

We are done with basic infrastructure code. In above steps, missing part is how to tell application code about which data source to be used from multiple data sources defined in context. It can be done by specifying the specific transaction manager (related to desired data source) with Service transactional attributes. Transaction manager can be defined either at class level or at method level. Or a good approach could be to use Transactional advice and define the transaction manager in context configuration with a pattern to identify the methods. 

A general workflow would be; whenever any service method is called using Spring Framework, Spring will see if there is any transaction proxy available for that method. If yes, transaction proxy will get invoked. It will work with defined transaction manager and will start a new or use existing transaction (based on transaction attributes). It will also try to attach the connection with the current transaction (thread local based implementation). Connection will be retrieved from the data source which is associated with the transaction manager (defined in context). This connection will be linked with current transaction as synchronized resource. Please note, that connection may be attached lazily in case of 'LazyConnectionDataSourceProxy'. In this way, Spring enables the scenario to use multiple data sources in application based on specified transaction manager.  All the methods invoked during the service call, or from nested methods will go to the database which is associated with current transaction manager (and the data source).

What is Functional Programming - II

In previous article, we have discussed about basic concept of Functional Programming in brief. Continuing with same, today we shall discuss more about it.

Although there are many concept in Functional Programming which are different than Imperative programming style. However, following four points are very important and differentiating factors. These are:

  • True Functions
  • First Class Functions
  • High Order Functions
  • Focus on result, rather than on structure and procedure to do it

True functions, we have already discussed in previous article. These are the functions without any side effect and is a main building block for functional programming. These makes the parallel and concurrent programming easier.

First Class functions are the functions which can be presented anywhere in a program, like a variable. These can be passed as argument to any function, can be returned as value from function, can be assigned to a variable or can be stored in a data structure. These functions are the basic building block in functional programming. Java like languages does not have this feature. One possible similarity can be an anonymous class only, which can be passed as argument to any function in Java, but that is also quite limited in scope.

High Order functions are the functions which can take First Class functions as parameter or can return these as return value.

Combining above two type of function, we can write very dynamic programs. Imagine, a variable is passed to a function with another logic definition and hence added all possible dynamic behavior in same method. We can do this in Java also, by passing some commands or executors etc. But it is not that flexible. In Java, anyhow, we need to write a class even when we only need an behavior. Functional programming allows to define the functions directly without thinking about class structure and allow to pass these to other methods. A much easier and quick implementation.  

Fourth and important point is that functional programming advocates the focus on result, rather than on procedure of implementation or structure. Following this concept, Functional Programming languages provides a lot of abstract implementations for various repetitive tasks, like for iterating over collection, for parsing and reading any element from XML etc. In a language like Java, our focus used to be on good Object structure and the implementation logic. While iterating over a list, we plan whether we should use index based iteration or should use iterator. For XML parsing, we plan which parser we should use and so on. However, functional programming languages hide these implementation details from the programmer and provides high level syntax for performing such functions. Now if implementation is hidden from programmer, and is being taken over by language itself, it means that any programmer can implement the program much faster in functional programming. However, it means we are banking upon language capability to make a good decision or logic to perform these actions.

Doesn't this feel like loosing control to the language. Like in Java, we have control over every piece of code. We can open the source code and can see how List.add is working. If we are not happy with it, let us extend the list and write a custom logic to add the items in List. Hence a complete control what we want to do. So is that OK to loose all control to language and just use the high level language syntax. A big doubtful point  from a programmer working with Java kind of language, hard to digest. What if language is not perfect, or having bugs.

However, let us see the positive side of this approach. If programming language is providing the abstraction for such repetitive tasks and implementation logic, it means lesser coding for a feature implementation. Less coding also means lesser issues in implementation and more outcome, more focus on business code and hence the result. Further, in most of the cases, implementation done by language can be much better than ours. We may not be expert in all logic implementation. And as and when language implementation will improve its implementation logic for functions, our program will be benefited automatically. Any improvement in code means improvement for our application also without making any change.   Eventually languages will try to have better and better implementation with almost zero bugs and better performance. Hence if language implementation is that good, do we really need to have control on these basic logic implementation. Shouldn't we focus our energy on writing something more meaningful for business i.e. the business application functionality. Lets put all our efforts for business features.

For a Java programmer, the program structure given by functional programming languages is hard to digest. It is a altogether new structure with much different organization of objects, and classes etc. But if we think, it is just another way of writing the program and it is good if we are getting more work done by writing lesser piece of code. For example, if we are interacting with computer or machines, we always want to get more work done by machine in smallest possible instructions. If we need to send an email, we always like a single command like 'Send Email to ABC with following contents', rather than to write a complete low level program to interact with mail server. Functional languages are only that kind of step for programming approach. These can make programming much easier task if used properly. And eventually we can reach to a point when one line of instruction will perform all required functions, for which we used to write a whole 2000 line class in Java. Actually Java is also evolving in that direction with many new utilities, AOP, lambda expressions etc. So this will be the requirement of future and is worth to embrace.

I hope it will help. We shall keep discussing more concept about Functional Programming. 

Solution - 'gem install mysql2' Fails

Today I spent some good hours to debug the issues while installing 'mysql2' gem. It was failing again and again stating that 'libmysql' not found (even after applying the solution I mentioned in previous blog). To share, I am mentioning all the steps from previous blog with today findings.

  1. Install 'MySQL' on your machine. Choose the installation depending upon your machine architecture i.e. 32 or 64 bits
  2. Have devkit installed on your machine. It can be download from 'http://rubyinstaller.org/downloads/'
    1. Download right installer for your machine i.e. 32 or 64 bits
  3. Install devkit by following instructions at 'https://github.com/oneclick/rubyinstaller/wiki/Development-Kit'
  4. Go to <MySQL installation dir>/lib and copy the 'libmysql.dll' to <ruby installation dir>/bin
  5. Try running gem install mysql or mysql2
  6. It should install now. However, if you still face problem, follow steps given below
  7. Try specifying the --with-mysql-lib and --with-mysql-include options with gem command by specifying the mysql installation respective directories
  8. If it still fails to load the 'libmysql', ensure that you don't have space in the path of MySQL installation directory. 
  9. Simple solution could be to copy the lib and include folders to a simple path like C:/mysql and specify the path of include and lib folder with gem command using --with-mysql-lib and -include options
  10. Hopefully it should resolve the issue
Hope it will help. 

What is Functional Programming

Today we shall discuss about Functional Programming in brief. Functional Programming is a different paradigm than Imperative style programming. Imperative programming includes change in states with functions, however, Functional programming advocates functions without any side effect, i.e. no effect on any of the state. This is a big difference in programming approach with many other implementation level differences.

Let us understand bit in detail, what is Functional Programming and how is that different than Imperative Programming.

For development using Java like language, we mostly follow Imperative style programming. Where a Class like data structure contains some state or represents state. Functions are implemented to work on this state. Functions make changes in states based on current state or passed parameters. End result is, once functions are executed, the shared states may be changed.

Functional Programming supports the concept of Pure functions. It states that function implementation should not have any side effects. It means that functions will not modify any state. These will only act on the parameters and will return the result. No state will be changed anywhere else. This also means that does not matter, how many times, you call these functions; if parameters are same then result will always be same.  This is one of the biggest difference in approach.

Let us discuss, how does this difference matter. With above understanding for Imperative style programming, if we want to support concurrent execution, we can apply concurrent programming concepts using threads and locks to safeguard the simultaneous update of states by multiple threads. We use different kind of locks, synchronized blocks etc to support the concurrent programming. Although with mature API support like java.util.concurrent, concurrent programming is getting much simpler now; but still it needs lot of care and knowledge to implement a perfect program. Moreover, we understand many scenarios only when program actually runs on multiple processors and scenarios changed with number of concurrent streams. So testing the concurrent programs is hard.

However, what if there is no shared state to modify through functions like in 'Functional Programming'. Then there is nothing to safeguard in concurrent or parallel processing. There is no overhead of locks and hence the concurrent scenarios testing. Results will always be same from a function irrespective of whether it is being executed by one or multiple threads by multiple processors. Functions just act on the passed parameters and return the result. Isn't that a big relief. Certainly, it can make parallel programming a lot more easier. Programmers can focus on business logic implementation instead of managing the concurrent programming scenarios. Further, it is entirely feasible and easy to process different functions in parallel on parallel processing units. Different implementation functions can be submitted to different processors. As there is no shared state to access or modify, so there is nothing for the processors to compete for. These can work parallel in harmony. So with proper designing, results can be utilized later from different processing units to form the final result.

From above discussion, it would be becoming clearer that Functional Programming is having edge when it comes to parallel processing and make it comparatively very easy to manage. This is one of the major difference in programming style and the benefits. That is why Functional Programming languages like Scala are getting popular. Why not, demand is for parallel processing after all.

There are many other differences also. Like, Functional Programming supports the concept of 'First Class' and 'Higher Order functions'. 'First Class' functions are, which can be presented in a program anywhere like any other first class member can present, for example anywhere like a Number type member, or as parameter or return value of a function. High order functions are, which can take other functions as parameter or can return these as return value.

We shall discuss  more for these implementation level differences and other concepts with coming articles. 

Vedic Math - Cube Roots

Today, we are taking a next level of topic i.e. finding the cube root. With normal approach, finding cube root is bit complex. However, using Vedic Math techniques, it becomes interesting and fast too. This amazing technique will help you to find out the cube root of a  4 or 5 or 6 digits number quickly and all using mind power only. Technique specified in this article will work for perfect cubes only, not for other numbers (that we shall discuss in forthcoming articles). Lets start learning.

We know that, cube of a 2-digit number will have at max 6 digits (99³ = 970,299). This implies that if you are given with a 6 digit number, its cube root will have 2 digits. Further, following are the points to remember for speedy calculation of cube roots (of perfect cubes).
  1. The lowest cubes (i.e. the cubes of the fist nine natural numbers) are 1, 8, 27, 64, 125, 216, 343, 512 and 729.
  2. They all have their own distinct endings; with no possibility of over-lapping (as in the case of squares).
  3. The last digit of the cube root of an exact cube is obvious:
    • 1³ = 1    > If the last digit of the perfect cube = 1, the last digit of the cube root = 1
    • 2³ = 8    > If the last digit of the perfect cube = 8, the last digit of the cube root = 2
    • 3³ = 27  > If the last digit of the perfect cube = 7, the last digit of the cube root = 3
    • 4³ = 64  > If the last digit of the perfect cube = 4, the last digit of the cube root = 4
    • 5³ = 125 > If the last digit of the perfect cube = 5, the last digit of the cube root = 5
    • 6³ = 216 > If the last digit of the perfect cube = 6, the last digit of the cube root = 6
    • 7³ = 343 > If the last digit of the perfect cube = 3, the last digit of the cube root = 7
    • 8³ = 512 > If the last digit of the perfect cube = 2, the last digit of the cube root = 8
    • 9³ = 729 > If the last digit of the perfect cube = 9, the last digit of the cube root = 9
  4. In other words,
    • 1, 4, 5, 6, 9 and 0 repeat themselves as last digit of cube.
    • Cube of 2, 3, 7 and 8 have complements from 10 (e.g. 10's complement of 3 is 7 i.e. 3+7=10) as last digit.
  5. Also consider, that 
    • 8's cube ends with 2 and 2's cube ends with 8 
    • 7's cube ends with 3 and 3's cube ends with 7
If we observe the properties of numbers, Mathematics becomes very interesting subject and fun to learn. Following same, let’s now see how we can actually find the cube roots of perfect cubes very fast.

Example 1:  Find Cube Root of 13824

Step 1:
Identify the last three digits and make groups of three digits from right side. That is 13824 can be written as          
   13  ,   824
 
Step 2: 
Take the last group which is 824.  The last digit of 824 is 4.
Remember point 3, If the last digit of the perfect cube = 4, the last digit of the cube root = 4
Hence the right most digit of the cube root  = 4

Step 3:
Take the next group which is 13.
From point 3, we see that 13 lies between 8 and 27 which are cubes of 2 and 3 respectively. So we will take the cube root of the smaller number i.e. 8 which is 2.
So 2 is the tens digit of the answer.

We are done and the answer is '24'

Isn't that easy and fun..

Design for Server Side Pagination

In previous article, we have discussed about various type of pagination and that how these work. We have seen that in most of the scenarios, server side pagination is better than client side pagination. Client side pagination can be used only if data, i.e. the number of records, are limited. In that case, we can consider to load all data on client side and may divide the data in pages while showing on screen. However, if data is large, we would prefer the server side pagination.

In this article, we shall discuss how we can design the server side pagination component. At first, let us summarize the requirements for server side pagination.

Requirements
  • Data is large enough to support the needs of server side pagination implementation, as discussed in previous article.
  • Only current page of data (or may be 1-2 more pages) should be loaded from data repository (DB), so we want to reduce the need to load large amount of data from data repository. The same or lesser amount of data should be loaded on client side.
  • User can navigate  through the pages using next, previous, first or last page kind of actions. 
  • User can also perform 'sort' and 'search' kind of operation on the data.  
With above requirements, let us design the Pagination Component now. 

Analysis and HLD

After analysis of above requirements, following are the main design requirements:
  1. Client - Any software program which needs to retrieve the large amount of data, but want to present this to end user (or application) in pages. Client can be a UI which is showing listing of data to end user, or may be a command line tool to show the data. 
  2. We need a component which 
    1. Can maintain the state for each client. Various states needs to be maintained are: 
      1. Current Page for which data is returned last time to client
      2. Number of records to be returned for one page
      3. Various data retrieval attributes required for fetching the page data from Data Repository, using data access component. These can be 
        1. Criteria to select the desired data 
        2. Sort criteria
        3. Search criteria
        4. etc
    1. Can work as a channel to retrieve the data from repository using data access components
    2. Can provide utility methods to client for accessing the data pages based on user requests like, next | previous | first | last | specific page number
    3. Can provide methods to client using which client can change various data retrieval attributes. This is to support the scenario, when end user change the search or sort criteria at UI.
  1. We need an abstract data access layer (can call it pagination data provider), which can understand the  language of pages and can return the filtered, and sorted data for specified page. 
  2. This component can be named as 'Pagination Manager'