A Prime Post

A prime number is a positive integer that is greater than one and has no factors except one and itself. One is not considered a prime number. 2, 3, 5, 7.. etc are some examples of prime numbers. Numbers that are not prime are called composite numbers. Here are the prime numbers less than 1000.

      2      3      5      7     11     13     17     19     23     29 
     31     37     41     43     47     53     59     61     67     71 
     73     79     83     89     97    101    103    107    109    113 
    127    131    137    139    149    151    157    163    167    173 
    179    181    191    193    197    199    211    223    227    229 
    233    239    241    251    257    263    269    271    277    281 
    283    293    307    311    313    317    331    337    347    349 
    353    359    367    373    379    383    389    397    401    409 
    419    421    431    433    439    443    449    457    461    463 
    467    479    487    491    499    503    509    521    523    541 
    547    557    563    569    571    577    587    593    599    601 
    607    613    617    619    631    641    643    647    653    659 
    661    673    677    683    691    701    709    719    727    733 
    739    743    751    757    761    769    773    787    797    809 
    811    821    823    827    829    839    853    857    859    863 
    877    881    883    887    907    911    919    929    937    941 
    947    953    967    971    977    983    991    997

So how do we find prime numbers?

One technique attributed to Eratosthenes of Cyrene (3rd century B.C) is called the sieve of Eratosthenes which allows us to find all prime numbers equal to or less than a specified number. The algorithm goes like this:

Start with all number from 2 to the specified number. For example, if we want to find all prime numbers less than or equal to 20, write down all numbers from 2 to 20.

2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20

Now remove all multiples of the first number (which is 2), from this list starting from the next position:

2, 3, 5, 7, 9, 11, 13, 15, 17, 19

Now remove all multiples of the second number (which is 3) from this list starting from the next position:

2, 3, 5, 7, 11, 13, 17, 19

Do this until you reach the end of the list. Now you will have the list of primes under 20 which is:

2, 3, 5, 7, 11, 13, 17, 19

The primes become more sparse as the numbers become larger and larger. So do they stop existing after we get to a certain point? In other words, is the list of prime numbers finite?

Euclid proved that there are an infinite number of prime numbers. He proved it using a technique called proof by contradiction.

To understand Euclid’s proof we need to learn about a theorem called the Fundamental Theorem of Arithmetic. This theorem states that every number greater than 1 is either a prime or is a unique product of primes.

Now let us move on to the proof.

Consider there are only a finite number of primes, say n. Let us represent this finite set as {p1, p2, p3…pn} where n is the total number of primes.

Let x = (p1 * p2 * p3 * .. * pn) + 1

Now ‘x’, which is one more than the product of the primes, should either be a prime or a composite. If x is prime, then the assumption that there are only n prime numbers is wrong. If x is a composite, then we should have a unique list of primes whose product will be equal to x (as stated by the Fundamental Theorem of Arithmetic).

Since x = (p1 * p2 * p3 * .. * pn) + 1, dividing x by any of the n primes would result in a remainder of 1. That means that there needs to exist at least one other prime number which would complete the unique list of primes that can be multiplied to get x. So our assumption that {p1, p2, p3… pn} represents the entire set of primes is wrong. To state it differently, there are infinite number of primes.


As a reader you might be wondering what prompted me to write this post. I have been reading about prime numbers and found many explanations of the Euclid’s proof online. Some were plain wrong and some had very cryptic explanation. So I spent some time thinking about it and reading many websites to get things clear in my mind first and then I thought I will share it here for the benefit of other searching for the same.

Little or Big?

Big endian and little endian. The endian-ness of a computer determines how it stores multi-byte data in memory. Consider the 4 byte integer 0x40302010. This is the hex representation of the integer 1076895760. Each byte can store 2 hex digits. So the number 0x40302010 would have to be stored in 4 bytes. If we were to store this number at memory location 100, would we store 40 at 100, 30 at 101, 20 at 102 and 10 at 103 or would be do it the opposite way – 10 at 100, 20 at 101, 30 at 102 and 40 at 103? Big endian computers do it the first way and little endian computers do it the second way.

Here is a pictorial representation of this. The memory address increase from left to right.

Big endian
100 ->
| 40 | 30 | 20 | 10 | —

Little endian
100 ->
| 10 | 20 | 30 | 40 | —

This is not a hard concept to grasp. But I could never remember which is which. Is big endian the one where we store the MSB first or is it the other way around. I always have to look it up.

Today, while waiting for a deployment to finish (perfect excuse to slack off now that compiling doesn’t take a long time), I was browsing some websites and I stumpled on the endian-ness of computers. I couldn’t remember which was which and I had to look it up. Again. Suddenly a flash of insight hit me – Little endian stores LSB (Least Significant Byte) in the Little address (smaller address). LLL. Little endian – LSB – Little address.

I think I have it etched in my memory now. This is a well known memory technique but its name escapes me now (oh the irony).

LG G3 Bluetooth Issues

Today I went for a drive on my CR-V which I have paired with my LG G3 via Bluetooth. Halfway through the drive my wife called me and I answered the call but there was no voice over the Bluetooth. I had to stop my car, remove the Bluetooth connection for the call and talk directly via the phone to have a conversation where we could hear each other. Just to confirm, I called her back via Bluetooth and the exact same problem occurred, we couldn’t hear each other. As soon as the Bluetooth was switched off everything was normal. As soon as I reached home I searched the internet to see if others had faced the same issue and not surprisingly I found many blog posts and discussions regarding the same issue. I have had this phone for about a month now and had never seen this issue until about a couple of hours after I posted a glowing review for the phone. Isn’t it ironic?

iPhone 6 Minus

For the past four years I was a loyal Windows Phone user. I didn’t have much qualms about the hardware or the operating system itself but the lack of apps made it hard to choose yet another Windows Phone when my contract was over and I was eligible to purchase a subsidized new phone in lieu of extending my contract for 2 years under the ever so evil AT&T. I was using an iPhone 3GS before changing to Windows Phone so I thought I would go back to the walled garden of Apple with an iPhone 6. A friend of mine had recently bought both the 6 and 6+ versions of the iPhone and the 6+ looked too big to me. It was hard to hold with one hand and I felt that I would drop it any time now. My Nokia 920 had survived many drops over the past two years, but I wouldn’t expect the fragile looking iPhone to do that.

Anyway, a couple of weeks ago I walked into our neighborhood Target with the intention of upgrading my phone and spent some time looking at the 6 and 6+ kept side by side on display. Having seen them side by side, I felt that the 6+ was better. The 6+ was $100 more than the 6, but the specs said that the 6+ battery would hold charge for 24 hours of talk time while the 6 would hold something like 14 hours (don’t remember the exact number now). That pushed me over the edge and I decided to go with the 6+ which was $279 for the 16 GB version (the usual price is $299, but Target had some deal going on which brought the price down to $279). I got a HTC One M8 for my wife which was an absolute deal at $0.01.

The iPhone 6+ is a very polished phone. The UI is crisp and responsive. The battery is awesome and easily last 2 days without charging (YMMV depending on how much you use). As fabulous as it was, it did have some quirkiness that ended up being a deal breaker for me. First and foremost, the lack of a back button is the most irritating feature of iPhone. I get all the design philosophy about less is more and so forth, but a back button is a fundamental element as far as I am concerned. Without the back button I felt lost with many apps. Many apps had their own custom back button built into the app. The problem with that is, each app implements it in its own way and it might take a bit of getting used to. With all their hullabaloo about great design, Apple fucked this up big time. Just add a back button Ive.

The second issue I had is about the available storage. I did not intend to store any music or movies in the phone so I thought 16GB ought to work for me. Turns out you get about 7GB after you have installed a few essential apps. Once I start taking pictures and videos using the phone camera, I would quickly run out of space. Both iPhone and iPad never provided the ability to add storage via an SD card. This is just Apple doing things in a particular way just because they can. Apple cleverly kept the entry level at 16 GB and the next one at 64GB to give the buyers the illusion of how great a deal the 64GB version is. Guess what Apple, we all know about this trick. A $750 phone ought to have at least 32 GB of storage (or the ability of add a SD card). Apple has a long history of fucking their customers which are the most loyal user-base any company ever had. I am not an apple fan boy and I wouldn’t take any shit from Apple out of sheer loyalty. I need value for my money and iPhone 6+ does not give that.

I exchanged the iPhone 6+ for an LG G3 and couldn’t be any happier. For one, I got the LG G3 for $0.01 for a 2 year commitment with AT&T. That is a saving of $300 right there (although if I manage to keep my iPhone flawless for 2 years I could sell it for $300 after unlocking it). The LG G3 comes with 3 GB of RAM and 32 GB of storage which is expandable to an additional 128GB via a microSD card. I have been using an Android tablet for a while now and I was immediately at ease with the LG G3. I immediately upgraded to Lollipop and thankfully have not had any battery issues that some users were complaining about the LG G3. Of course I have set my screen brightness to automatic since the screen is the biggest battery hog on the LG G3 and I don’t continuously check email or whatsapp, so I might not be a heavy user. I get 1.5 to 2 days easily on the phone between charges. My wife got the HTC One M8 and she is quite happy with it too.

All in all, if you are a current iPhone user and have gotten used to the lack of the back button, and you have money to spare you would definitely like the iPhone 6+ with its big display and good battery life. But if you are switching from a Windows Phone or Android phone, you might be soured by the lack of extensible storage, lack of back button and higher price.

A Year Without Posts

2013 went by so fast. Just in case you did not notice, no blog entries were posted here. Was it because I was lazy? Yes. But not just that, I thought it would nice to take a break. Why? I don’t know. Why do you think I have all the answers?

2013 was a good year for me both personally and professionally. I will not be going into details of those here. Why? Because I am lazy, I don’t want to type that all in. Then why bother mentioning it at all? I don’t know. It sounded like a good idea when I started typing.

I was expecting a big public outcry when I stopped blogging last year. I wanted it to be a big event, kind of like when Joel Spolsky stopped blogging. Maybe, I thought, some folks would show up at my door steps and beg me to come back. They would organize rallies, throw stones at government buildings, burn some buses (without any people in them, of course, I strongly oppose doing otherwise) and maybe occupy wall street. Just to be clear, the intention of these should be to force me to come back, not to celebrate the event. At the very least, I expected some encouraging comments from my readers saying that they miss me and that I should write something just to keep them going through this tough journey called life. Alas, nothing of the sort happened. Even I forgot about it most of the time.

Now I think I should resume blogging. What if my fans really missed me? What if they are just shy folks who are not the type who would show up at their hero’s door steps to beg for more? What if they are the silent types who don’t like to comment on blogs? The more I think about it, the more I am convinced this is exactly the case. Because if I look at all my previously written pieces, none of them have many comments, if any at all. What more proof do we need for the theory that my fans are the quiet types, the ones who likes to read my blog over and over again, but never courageous enough to venture a comment. I have to be understanding of them, don’t I?

I love you folks, my dearest fans. I don’t want to leave you in the dark to fight alone. Here goes.



2012 was one of the worst movies of all time. The year 2012, however, was not so bad. Of course not everything went the way I wanted but overall it was not a bad year at all. My new year resolutions included five things and I achieved three of them. 60% success – that is a new record for me. Usually my new year resolution success rate is 0%.

My new year resolutions are usually fringe things on which it is hard to concentrate on for prolonged periods of time, especially when life presents more important challenges to deal with. After years of setting goals for the new year and failing to get anything done consistently, now I know that the trick to having new year resolutions that you can achieve is to have a few of them (2 or 3) that you really really want. “Good to have” things just don’t cut it. It should be “must have” things – things that are really important to you. And it should be no more than two or three things.

An important thing to keep in mind while executing your resolutions is to evaluate your progress continuously. You should do that at least every three months. That will provide a good deal of motivation. If you are running behind, it will give some renewed enthusiasm to get back on track. If you are on track, you will get a feeling of satisfaction and deep down you will know that this is something you can do. Either way, you win.

The things I did not achieve for 2012 were reducing my weight by 15 lbs and studying algorithms and data structures. At one point I reduced 5 lbs without any kind of dieting. I was exercising regularly and playing volleyball. Then I injured my wrist while playing volleyball and I stopped the exercising and volleyball. I gained back all the weight in a couple of weeks.

One of things I wanted to achieve was to write 12 blog posts in this year. You guessed it, this is the 12th one. If I didn’t have it as a goal I probably wouldn’t write this one. Not that it makes much difference but it makes me understand that having a goal puts one in a more advantageous position to achieve it. So I will make new resolutions for 2013 – maybe 2 or 3 ones that I really really want to achieve. The kind of ones that will keep the fire burning, the ones that makes it worth the effort.

So long, 2012. It was nice knowing you.

No country for old men

Like many brand conscious and price conscious people in America, we went for some midnight shopping yesterday. Black Friday, as it is called, is when people who are normally normal loses all sense of decency and common sense and push the people in front of them in the queue, or trample over them, with a sense of urgency seen on a sinking ship, and fill their shopping carts with junk that they will probably never use and then stand in a queue for an hour or two to give their hard earned cash to giant corporations so that their CEOs can buy yet another villa in the South of France.

While all that madness is quite disturbing in its own sense, what disturbed me even more is that I found that I don’t really have the energy or inclination for this kind of partying anymore. I still like to buy all that junk that I don’t need and then worry about where I can find the space for it, I found myself a little separated from the crowd. I am figuratively speaking here, because I would have loved to separate myself my those people knocking me over in a hurry to get to that gadget that they so desperately want, but there was no space in the mall for that kind of tranquility. You just keep moving forward in that river of people, flaying your arms around, grabbing at whatever pieces of merchandise you can get your hands on. What surprises me is that we are supposed to be in some kind of recession. I shudder to think of days were everybody is doing well. Anyway, as I was saying, I found myself quite tired very soon. The passion to amass pieces of junk, which I showed so furiously in the previous few years, was missing. My legs were aching, my hands tired and the spirits quite low.

I wonder if this is a sign of getting older ? Would I never again enjoy losing a night of sleep for the simple joy of watching capitalism in action ? Am I getting so mature that material wealth doesn’t give me any pleasure ? I hope not, because what is life if you can’t push some smelly college kids our of your way, trample over a few fellow country men and grab that last piece of gadget on sale.

Getting caller information in C# 5.0

In application log files, sometimes it is really useful to see the name of the method that wrote the log, the source file and the line number. If we were using C++, this information would be readily available to the logger using some convenient macros. But if we are programming in C# 4.0 or earlier, we had no way to get that information automatically if we don’t have the debugging symbols (except for the method name) and we don’t usually deploy the pdbs along with the binaries. Even if we did, the line number is almost always different between debug and release builds. Unless we build our binaries in debug mode and then deploy the pdbs along with the binaries, which is not usually the case, we are out of luck. The other disadvantages of using the StackFrame class to get the method information is that it is slow and if your code is obfuscated, the name of the calling method will not be what we expect.

The way I have seen it in most logging code in C# is the calling method’s name is passed into the logging method as a string but the caller’s source file and line number are usually not logged. Although it is possible to pass in all this info to the logging method, it is such a chore and a maintenance nightmare. The name of the method, the source file and line number can all easily change and one can just as easily forget to update the logging code. Anyway who wants to pass in all that information when all they want to do is log a message.

C# 5.0 introduces a way to get the caller information in an easy and non-intrusive way. While the design is not what I would call the most intuitive, I am happy that it works with minimal disruption to our existing code. We can get three pieces of caller information using three attributes that can be applied to optional parameters of a method which is interested in getting information about its caller. The attributes are

  • CallerMemberNameAttribute
  • CallerFilePathAttribute
  • CallerLineNumberAttribute

Here is an example of how we will use these attributes:



        publicstaticvoid Log(

            string message,

            [CallerMemberName] string caller = “”,

            [CallerFilePath] string filePath = “”,

            [CallerLineNumber] int lineNumber = 0)



                “{0}. Caller {1}, src file: {2} on line #: {3}”,







The compiler will automatically fill in the correct values for these optional parameters at compile time. How convenient !

Read more here.

Canadian immigration for Software Engineers

If you are a software engineer looking to immigrate to Canada, or at least apply for permanent residency as a back up plan while waiting for your US green card, you might be interested to know that you can apply for PR in Canada this year. A couple of years ago, occupations for software engineers were removed from the list of occupations eligible to apply for PR in Canada. If you were disappointed that you didn’t apply for it before it removed, then this your chance. Read more details here.

async and await in C# 5

C# 5 comes with just a few new features and async is arguably the more important of those. I have started looking into it a couple of days ago and I thought I would share my thoughts on it here.

Asynchronous programming was touted was the next big thing for quite some time, but it didn’t hit mainstream in the .NET world till recently. Well, people were always using threads from .NET 1.0 but it was hard and error prone to write multi-threaded programs. Library support and tool support was lacking. The Task Parallel Library (TPL) introduced in .NET 4.0 was a step in the right direction. In this context, making asynchronous programming easy for C# programmers is probably the right thing to do as far as Microsoft is concerned.

Two new keywords have been introduced in C# 5.0 to make working with asynchronous code easier – async and await.

The async keywords is used to mark a method as asynchronous. It is required to use the await keyword inside that method. Note that just marking a method with async does not make it asynchronous. In face you can write fully synchronous code in a method marked as async, and the compiler will be ok with that.

        async void NothingAsynchronousHere()


            Console.WriteLine(“This method is executed synchronously”);


Actually, the compiler is not completely ok with that, when you compile the code you will get a warning:

“This async method lacks ‘await’ operators and will run synchronously. Consider using the ‘await’ operator to await non-blocking API calls, or ‘await Task.Run(…)’ to do CPU-bound work on a background thread.“

Now let us look at an async method which is actually asynchronous:

        async Task<string> GetWebpage(string url)


            WebClient client = newWebClient();

            var response = await client.DownloadStringTaskAsync(url);

            return response;


This method shows how the await keyword is used. This method looks like a synchronous method, but it actually executes in 2 phases. The calling thread executes upto client.DownloadStringTaskAsync() (which is an asynchronous method and it returns immediately). After that the thread immediately returns to the caller of GetWebpage. The caller can chose to wait (remember, GetWebpage returns a Task<>) or continue its own execution (and maybe later get the result of the download using the Result property of the Task<>). Once the download completes, the rest of the lines in the async method is executed. Usually these lines of code are executed on the same thread as the calling thread (which means you don’t have to worry about accessing UI controls if the async method was invoked using an UI thread) but there are some cases where it won’t be the case (an example being using a Threadpool thread).

Here are some things to remember. An async method can return only void, Task or Task<>. Otherwise the compiler will complain:

The return type of an async method must be void, Task or Task<T>

Another thing to keep in mind is that you can await only on methods that returns Task or Task<>. This means that you cannot await on WebClient.DownloadStringAsync() since its return type is void.