Saturday, March 12, 2011

C Program to print armstrong numbers in a given range of numbers

Program
#include <stdio.h>

int main()
{
  int num,n,m,digits,sum,a,b,i;
  
  printf("\nEnter the range (a b): ");
  scanf("%d %d",&a,&b);
  
  num=0;
  for(i=a;i<=b;i++)
    {
      if ( i == a)
         {
            digits=0;
            m=i;
            while (m != 0)
               { 
           digits++;
                  m=m/10;
               }
          } 
       
       if ( (i != a) && (i/power(10,digits) == 1)) digits++;
          

      sum=0;
      n=i;
      while (n != 0)
 {
   sum=sum+power(n%10,digits);
   n=n/10;
 }
      if (sum == i)
 {
   printf("\n%d is an Armstrong number\n\n",i);
   num++;
 }
    }
  printf("\nThere are %d Armstrong numbers in the range %d - %d\n\n",num,a,b);
  return 0;
}

int power(int x, int y)
{
  int xpy,i;
  
  xpy=1;
  for (i=1;i<=y;i++)
    xpy=xpy*x;
  
  return(xpy);
}

Compilation, Run and Output
[sreedhar@manchu2 cprograms]$ gcc armstrong_range.c -o armstrong_range
[sreedhar@manchu2 cprograms]$ ./armstrong_range 

Enter the range (a b): 11 1000000

153 is an Armstrong number


370 is an Armstrong number


371 is an Armstrong number


407 is an Armstrong number


1634 is an Armstrong number


8208 is an Armstrong number


9474 is an Armstrong number


54748 is an Armstrong number


92727 is an Armstrong number


93084 is an Armstrong number


548834 is an Armstrong number


There are 11 Armstrong numbers in the range 11 - 1000000

[sreedhar@manchu2 cprograms]$

C Program to check whether a given number is an Armstrong number

Definition: Armstrong number is a number that is the sum of its own digits each raised to the power of the number of digits.

Program
#include<stdio.h>

int main()
{
  int num,n,m,sum,digits;
  printf("\nEnter the number: ");
  scanf("%d",&num);

  digits=0;
  m=num;
  while (m != 0)
    {
      digits++;
      m/=10;
    }

  sum=0;
  n=num;
  while (n != 0)
    {
      sum=sum+power(n%10,digits);
      n=n/10;
    }
  if (sum == num)
    {
      printf("\n%d is an Armstrong number\n\n",num);
    }
  else
    {
      printf("\n%d is not an Armstrong number\n\n",num);
    }
  return 0;
} 

int power(int x, int y)
{
  int xpy,i;
  
  xpy=1;
  for (i=1;i<=y;i++)
    xpy=xpy*x;
  
  return(xpy);
}
Compilation, Run and Output
[sreedhar@manchu2 cprograms]$ cc armstrong.c -o armstrong
[sreedhar@manchu2 cprograms]$ ./armstrong

Enter the number: 152

152 is not an Armstrong number

[sreedhar@manchu2 cprograms]$ ./armstrong

Enter the number: 153

153 is an Armstrong number

[sreedhar@manchu2 cprograms]$ ./armstrong

Enter the number: 1634

1634 is an Armstrong number

[sreedhar@manchu2 cprograms]$ ./armstrong

Enter the number: 54748

54748 is an Armstrong number

[sreedhar@manchu2 cprograms]$

Starting and Quitting Applications on Mac OS X through AppleScript and iCal

This time some useful stuff here unlike my previous posts which were nothing but useless ramblings on my life. At my job I need to be on Adium application all the day. If you don't know what Adium is it's nothing but free IM client for Mac OS X that supports multiple IM networks like Google Talk, Yahoo Messenger, etc.

Early in the morning, as soon as I go to work I don't have problems to remember to log on to Adium. But most of the times I tend to forget to log out of it before I leave at the end of the day. So, I thought of making it automatic through some script. Since my OS is Mac OS X I thought it would be better if I used AppleScript. So started my foray on to it.

My script looks like below to start and quit application Adium. You can pretty much start and stop any application like this by replacing Adium with it's name.

Script to start the application
tell application "Adium"
    activate
end tell

Script to stop the application
tell application "Adium"
    quit
end tell

I don't think there is any need to explain the script as it is self explanatory. This is a very trivial script. You can do crazy stuff with this AppleScript. Just google for it and you find tonnes of pages.

As you can see it doesn't tell anything about the time it's going to start and stop Adium. Good catch! The trick is to use iCal for this purpose. Create a new event and under alarm options choose "run script". It let's you choose your saved above script. In the event you can specify at what time everyday it should start. For example, I set up two recurring events on week days. First event starts at 9AM and runs the first script. I named the script as start_adium. The second event runs at 5PM and runs the second script through alarm settings which I named it as stop_adium.

That's it. Now it's automated to start and stop Adium on every week day. Cool. Ha! But there are disadvantages to it too. Even if you are not on time to the office script gets run exactly at the specified time. Which means people think that you are there in the office. Again I don't care about this and it works for me. I'm sure there must be ways to write a script to make it start and stop as soon as you unlock and lock the screens. I guess no one forgets to lock the screen if he is a system admin. Right? Since I have this idea right now I'll try to look into this and let you know if I find something.

Note: Use shortcut "Command + Space bar" to initiate Spotlight and type applescript. As you type you would see AppleScript Editor next to applications. Hit enter and you see an AppleScript editor to write your script. Just for start, you can copy my script on it and run it to see what happens. Use some other application name in the place of Adium if you don't have it on your system. Hope this helps someone.

Friday, August 27, 2010

Hope for a new beginning

It's been a while since I wrote my last blog. Not much has changed in all this time. I'm still struggling to find a break. I've always thought that it'd be easy to survive once we find some initial break. The trick is finding that break. The only changes that took place in my life since my last blog are I moved to a new place and I've started playing the league again.

My lease for the last place was over last month. I was so broke I clearly understood one thing for sure that it was expensive to stay at that place. It was kind of crazy to pay $1200.00 for studio apartment. Since I'm totally broke, now I'm not in a position to pay for rent. So I'm staying with my friends hoping that one day I'd be able to find a job and get my own place.

Coming to the second change, yep I've started playing the cricket league again. I've always excelled in the cricket field. I'm definitely not a very quick bowler. When I first joined engineering college, I think I was genuinely quick. I could always change my bowling action to generate more pace apart from tricking batsmen. I'm not sure whether it is the age or my back surgery 4 years back that caused drop in my pace. Now I definitely don't bowl that fast anymore. But all my life until now I've always known how to swing a ball. I think it always brought me lot of wickets. That too I always got very good batsmen. When ever I get to bowl these days, with out hesitation I try to bowl variety of balls. It took long time to understand it really doesn't matter even if you get hit while trying to bowl something different.

Anyway, coming back to present situation regarding my job search the only positive thing I've noticed is I'm getting calls from employers. At the beginning of this month I was very excited to get a call from Nvidia. Of course, after that call I was expecting another call but it never materialized. It would have been great if I did. In my opinion GPU computing is the future. CPU days are over when it comes to higher performance computing. May be that's an overstatement. I can say it's going to be GPU in the next few years. I thought if I could get into Nvidia I'd be walking down the brightest path for the future. May be it's not meant to be.

Then there was a call from Cray, Inc. I guess working for any supercomputing company would be awesome. Recently, I've applied for lot of HPC jobs and I'm hoping to get into one of those big companies like Intel, Nvidia, etc. If I could get a chance to attend an interview, I think I can pull it off. It's a matter of how well you can convince them of your abilities. After that it all depends on how good you are at doing stuff. I think I can do good programming. I've never hesitated to say I can be a good programmer. Unfortunately, until now I've never got a chance. Hopefully it should all change in the near future.

This season I've played 4 matches so far. First 3 matches were patchy in terms of my performance. I guess I bowled well if not exceptional. I think I switched gears to an extra level in my last match. I did very well in every department. I batted down the lower order and played a crucial innings to save my team from sinking. I played some audacious shots. In the end it felt great when my team mates and people from other team congratulated on my batting. Then it self I was sure that I'd bowl well.

Luckily, this time I got a chance to open the bowling and I stuck with my 2nd ball it self. For some reason, I've always loved to bowl at left handed batsmen. I've always loved the challenges like bowling to left handed batsmen. It's a challenge because of one simple reason. Most of the people find it very difficult to bowl to left handed batsmen as they'd have to change their side and shooting angle. I've always loved to make my self excel where other people find it difficult. Like I said I can swing both ways and in my last 2 matches I bowled exceptional balls to bowl 2 left handed batsmen. In my third match I bowled an in-swinger so good that it took middle stump from no where. It landed almost a foot away from the off-stump and batsman had no idea when it swung in late to take off his middle stump. Worst thing was it was no-ball. Anyway, by then that match was in our hands and so it didn't cost us.

In my last match opener from the other team was left handed batsman. My friend told me that he was division one player. This time I bowled an out-swinger to him. But the fun part was I made it to land some where in between off and middle stump. Batsman played perfect defensive shot. But I'm sure he didn't expect it to go through his defense. It was beautiful sight. It was great because it had to go to swing out of it trajectory to beat the bails on the off-stump. It was like going towards leg stump and in the final seconds it changed it's trajectory and narrowly beat his bat and then took of the bails. It was just out right beautiful out-swinger I've ever bowled to left handed batsmen in all my life. I honestly believed it would take out any left handed batsman.

Unfortunately, I couldn't continue bowling as I got severe cramps in my second over. I had to leave the field in severe pain. I knew that my team needed me and so took lot of fluids in that break to go back into the field. I went after the first break and had to wait another 10 overs before I could bowl again because of the bowling after retired rule. In a way it was very good match considering it could have swung either way until the end of the match. Finally, I took my chances to start my second over in the 33rd over and the other team had only one wicket to make winning runs of 20. Their plan was to stay there and runs would come on their own. I guess it was a very good plan considering I was the only bowler left with overs. Which means some other guy had to bowl in tandem with me. It would have made easier for them to get those runs considering we didn't have any other good bowler to bowl with me. All other strike bowlers had already finished their quota. So I took the over in the hope of finishing the game. My captain put faith in me to do the task and I duly did. This time it was a very conventional trick that got me the wicket. I'm sure you must have seen this number of times in your life. Bowler bowls 3 out-swingers, good ones, and then finally put an in-swinger. I executed my plan to a T that it took out the middle stump. Some times you bowl an exceptional out-swingers and still don't get a wicket. Even though I love to get wickets with out-swingers, it's always the other one which gives pumps you up with adrenaline.

It was great when I finished the game like that. I didn't care to jump in the air even though I knew it would bring my cramps back. Luckily, nothing happened like that. I guess drinking all those 2 liters of fluids did the trick. This time I make sure that I take enough fluids it won't happen again. I felt it was a very good performance. Worth of man of the match. I got the ball as a souvenir. The only thing that bothered me was my fitness. It was shocking to understand how low it was. While batting I was out of breath through out my innings. But I guess I was the best runner in my team. I mean fast runner. I believe in taking singles to propel an innings. Plain old theory from God of Cricket, Sachin bayya. Some times I wish I could have those big shoulder muscles to hit big sixes. I hit some good shots using timing. I'm sure they would have been big sixes if I had power in them. I just timed them well to make them fours. Still it was good because all those drives gave me an immense confidence as well as satisfaction.

I know it's a kind of overdoing writing all about it. Believe me you'd also feel just like this when you do something that makes you feel awesome like this. More over like I wrote before nothing is moving forward in my life and I think I need these kind of moments. Hopefully, I can help my team keep winning the matches and this would make me feel great too.

Just yesterday I got a call from one of the companies located in LA and I'm hoping to get this offer. If I could get it, then I could stay here in LA and be with my friends and play cricket. Hopefully it should go just like this. Then definitely, it would be a new beginning. Want to write more, but need to take care of something else. I'll write again very soon. Need to clear my mind off lot of things.

Sreedhar.

Thursday, July 1, 2010

Difference between hand compass and car compass?

The other day it came across my mind. There is a subtle difference between these two things. Hand magnet shows the direction by pointing it's arrow towards that direction. Where as the car compass points the arrow opposite to the direction we are heading so that we could see the direction symbol.

For example you are driving your car heading north. If you had a general compass, the arrow with north mark should point away from you towards direction north. But you are sitting inside the car and you can't afford to see the arrow from your side. It could be dangerous too to look at the magnet lying some where next to you. Of course, if you are walking then it's easy for you to keep it on your palm horizontally and see the arrow to figure out the direction.

Where as car compass would be hanging by windshield in front of you in your car. So when you are driving towards north, the car compass should let you know that you are driving north by showing you arrow with north symbol just like the other one does. That's why it shows the north arrow towards you exactly opposite to the direction you are going. Which means they put the symbols on the opposite arrows of original directions. For south you see north and vice versa.

The simple reason for this is the general compass would be some where so that you don't have raise your head upwards. Where as for car compass you need either to raise your head or align your vision with car compass hanging down a windshield.  Even if car compass shows the original direction north when you are driving north on the north side of the magnet, then how can you see the arrow with symbol as it would be away from you on the other side of the magnet. That's why they swap the symbols. Cool. Right?

Some times we just use things and we never think of these small things. For example, you have car compass in your hand and you try to go some where following that. That's it you end up in the wrong direction if you don't know the funda behind it. So be careful when ever you have a compass in your hand to know which one it is. Otherwise you might end up in trouble.

Maps and directions

When I was small kid I was always curious about geography. At one point I remembered names of every country and it's capital city on this earth. I was very interested in looking at earth maps. Looking back it's amazing to see how much has changed over the years. Now people take their gadgets and type the address and bam it gives you the directions. In the old days it was just maps on paper. I still think maps on paper are cool compared to all these electronic maps. If you know how to use these paper maps you know how to locate directions on your own even in the new places or in the places where there is no signal for your cell phone.

Anyway, I want to write how I figured out certain things when it came to finding which direction I'm heading. All these things might sound simple to you. But I'm sure given the situation all these things never come across one's mind.

One day I was walking through the Glendale city and suddenly I had no clue which direction I was heading towards. The good thing about walking is you can simply look at the street names and immediately you know the direction. For example, you are walking on Brand Street and if you look at the street signs, you see either N. Brand St. or S. Brand St. Which means you are either walking south or north.

Then the second thing is to find south or north. The way streets are divided into two halves is by doing it from the center of the city. For example, in Glendale city the intersection of Brand and Broadway is considered to be the center of the city. So, Brand is divided into South Brand and North Brand from the Broadway Street. For example you are walking on south part of Brand street. There could be many cross streets before you see the Broadway street. Which means even if you are heading towards north, you could be on the S. Brand St. for long time. Which means until you don't cross Broadway you don't see N. Brand St. even though you are walking towards north on Brand Street, to be precise towards north on S. Brand St.

So how do you figure out the direction? Simple. Look at the numbers on the street signs. Generally, you see something like 400 S. Brand St., 300 S. Brand St. etc on the street sign boards at the cross sections of the streets (here streets crossing through S. Brand St.). I've already told you that they divide the street from the center of the city. Which means, on S. Brand St. the numbering starts from number 1 in the increasing manner towards direction south. Similarly, numbers increase towards north direction on N. Brand St. Which means if you are walking towards North on S. Brand St. the numbers on the sign boards keep decreasing as long as you walk towards the center of the city. Finally it goes to the number 1 and immediately N. Brand St. starts and the number again starts from 1 but this time increases if you are still walking north.

Otherwise, i.e., if the numbers are increasing on S. Brand St. then you are walking towards south. Same with N. Brand St. I mean, if you are waling on N. Brand St and the numbers keep increasing on sign boards then you are walking north. Otherwise, you are walking towards south. As simple as that.

Same rules apply for the streets aligned in the east and west directions. Which means, even when you don't have maps or cell phone or gps gadget with you, you still should be fine as long as you know which direction you should head to go to your place. If you really don't know in which direction your place is located, then you are definitely screwed. Even then it's no big deal as long as you are not nervous or tense. Just go to gas station and buy one map. Then you can figure out where your place is located and which routes you should take to reach home.

I strongly believe that if you look at paper maps you never forget the entire layout and you get the big picture of city directions printed on your mind. Otherwise, at least try to spend some time looking at google maps and get yourself well acquainted with city layout.

Before I figure it out, one day I went to airport to leave my friend. When he asked whether I'd be fine to go back home from LA airport, I gave him very confident answer even though I didn't have my cell with me to look for directions. The reason for my swagger was that I knew the directions by then. Funnily, when I went there to take the highway, the entrance was closed and I was screwed big time. I had no clue which way I should go from there and I was simply driving in some direction.

Still I was not tense or worried though. The best thing one could do to himself or herself is not to panic in situations like this. More over I didn't have any cash on me or credit cards. The only thing I had with me was my driving license. Of course, just to look for directions I don't have to buy maps but just have a mere look at them. Still, I didn't want to do that as I was not sure how store assistant would feel if he caught me doing that. Anyway, the point is I didn't panic since I knew some what about these highway numbering system and which highways would take me home.

So, I kept on driving for a while in some direction. The one thing I knew for sure was the airport was next to ocean in the west. So if I kept driving and if it was west direction, then I should see the ocean. But I never saw it, so I took right turn and kept on going. Finally, I saw the ocean and I was like ok now I'm driving towards west. Then I went in the opposite direction until I saw some highway. From there some how I figured out.

Even then I had to have known the highways earlier. Otherwise, it would have been tough. Ok now what's the lesson I learned from that trip? Simple. Always carry some cash on you or at least credit cards. Make sure that you have your cell phone, that too fully charged. The other thing you should do is to have paper maps in the car. They would come very handy. Other simple thing that would come very handy is car compass. You could just put it there on the windshield and you know the directions all the time.

In the end, no matter what gadgets and stuff you have with you, it really doesn't matter as long as you don't use your brains. The more you depend on gadgets the more numb your brain becomes. There are even ways to figure out directions by looking at your own shadow.

I'm sure you must be thinking I must be having tonnes of free time to figure out these things. Yes, sadly I do. Still I take pride in myself in figuring out things like this. I'm very confident that I could come out of any situation like getting suck some where in forests.

In the end we should never forget the fact that we are all given brains. So let's put them to use at least now and then. Now, once I figured out how to know the directions by looking at the street signs and by having the city layout, I feel like I don't need directions to go some where. I look at them one time and I'm good to go as long as I can afford to figure out the directions when something goes wrong. Key is start early.

Daylight saving time

Wanted to write about it for long time. I don't remember when it crossed my mind first time. When I was doing my masters in Sweden, I guess I came across the method of adjusting time at certain point of time in a year. In a way it confused the hell out of me to understand why it was adopted. Eventually, I came to know that it was introduced to lower the consumption. I guess it makes sense as in the old days lighting was the only form of electrical usage. It seems they wanted to add the daylight to afternoons and reduce the light in the mornings. If you don't know what it is, let me explain to you. It is a practice of advancing clocks so that afternoons have more time and mornings have less.

Anyway, coming to the point, almost a year back I was talking to one of my friend about it and we couldn't figure out whether it was in effect during the winters or summers. Later, looking at wikipedia we were able to figure out the answer. Then I kept on thinking about it and came up with some solution of my own to find when it would be implemented in a year.

In my home country, India, we don't use daylight saving time since our daylight pattern doesn't change much through out the year. Which means we don't advance the clocks at all at any point in a year. So I thought I could take it as a reference point. Even better reference point is GMT (Greenwich Mean Time) which doesn't change just like Indian Standard Time (IST).

We always take GMT as reference when ever we want to mention the time in different time zones. For example, for now football world cup is happening in South Africa and when ever they publish schedule they do it in reference to GMT. Which means Greenwich longitude is zero degrees. Of course, you don't have to think all of this to come to this conclusion. If you know the map, you simply know that Greenwich, London is on zero degree longitude meridian.

The second step is to find the longitude of some time zone in US. I took eastern time zone and took the longitude of center of this zone from the map. You can get it from the google maps. Generally, 75 degrees is considered for the eastern time zone. So now you know that the longitude difference from Greenwich to eastern time zone is 75 degrees.

As all of you know, one degree of longitude constitutes for 4 minutes in time. If you don't know how I came to this conclusion let me explain it to you. There are 360 degrees of longitudes that go through the earth from east to west. Of course, we need to consider only longitudes since earth always rotates towards east and this is the reason you see the sun in the east when you wake up early in the mornings. Latitudes refer to north-south directions. You all know that it takes 24 hours to complete one rotation around it self. To be precise little less than 24 hours and this is the reason we employ leap years to offset this value. So it takes 24 hours for 360 degrees. Hence it takes 24/360 hours for one degree of longitude. Which comes to a value of 4 minutes (24hours=24*60 minutes).

So now you know that the longitude difference of 75 degrees comes to 75*4=300 minutes=300/60=5 hours. Which  means if the time in Greenwich is 9PM and since Greenwich is east of US, we subtract 5 hours from this time and we get the eastern standard time which is nothing but 9-5=4PM.

But when we did the calculation the time in the eastern zone was 5PM. It was summer and I was elated to know that my theory proved to me that daylight saving time would generally be employed during the summers. Of course, like I said it makes sense since they wanted to advance the clock so that afternoon would have more time. Which means there would be no need to turn on the lights in the evenings as we are advancing the clock.

Ok let me put it this way. For example, at your place during the summer sun sets around 7 in the evening. But during daylight saving time we advance our clocks one our ahead which means time would be 8 in the evening. Right? Of course sun always sets at the same time. It's just we are the ones changing the time by advancing the clocks. So you were used to turning on the lights around 7pm and since we advanced the clocks by one hour you would be turning on the lights around 8PM there by saving one hour consumption of electricity.

In the old days electricity consumption was a big issue and hence they came up with this idea. It no longer is a issue, but still people are stuck with the tradition I guess. At the same time you can argue that how about the mornings. I mean consumption in the mornings. How many of us turn on the lights in the mornings. I mean, by the time we wake up in the mornings there is already sun and so there is no need for lights. Generally, during summers sun comes up by 5 it self. So even when you advance the clock by one hour sun comes up at 6am. Not that much difference considering most of the people don't wake up at 5am.

Finally, just to let you know the clocks are adjusted backward later in the winters. Which means we lose one hour time on that specific day where as we gain one hour on the day when the clocks are adjusted one hour forward.

Over all, I found it to be very fascinating the way it came into existence. Awesome. In the end my theory made me feel happy that I was able to prove that daylight saving time is employed in the summers.

For long time, I wanted to write about it and finally here it is. Next time I'm going to write something about maps which I found very interesting. Believe me, you will too even though it might sound very trivial to you. I'm sure what ever I wrote until now might be nothing. Just curious, did you know all this before you read this or if I asked you to prove it, would you be able to do it on your own with out looking at any web sites like wikipedia? If not, then don't you think you learned something new?

PBS Script Generator: Interdependent dropdown/select menus in Javascript

PBS SCRIPT GENERATOR
SH/BASH TCSH/CSH
Begin End Abort

About Me

LA, CA, United States
Here I write about the battles that have been going on in my mind. It's pretty much a scribble.

Sreedhar Manchu

Sreedhar Manchu
Higher Education: Not a simple life anymore