Thursday, January 6, 2011

Sum of numbers until single digit

When you buy a vehicle in india the registration number assignment for the vehicle will stay for ever(per my knowledge, not sure if there any way to change the number some time later). Always people prefer and think certain numbers(sum of numbers until signle digit) are considered to be auspicious. So they usually say, I want a number 9 or 3 or 1 etc.(between 0 to 9).

If you pay some money, Motor registry office will provide you 1000 numbers(like choose number between 853 to 1852) and you can choose one number from that 1000 numbers(there is a possibility that some number might have taken already with in that 1000. So you have to keep telling your favorite numbers and choose the one available in that).

I also ran into this situation and want to choose the lucky number 9. It's hard to list all numbers its sum is 9. So I wrote a small Java program where you can specify the lucky number, starting number and end number, it will print out all the numbers matching you lucky number. I thought it might be useful for some of you, so putting this program in blog.


public class VehicleLuckyNumber {
final static int LUCKY_NUMBER = 9;
final static int STARTING_NUMBER = 853;
final static int END_NUMBER = 1852;

public static void main(String[] args) {
int count=0;
for (int i=STARTING_NUMBER;i<= END_NUMBER; i++) {
if (sumValue(i)== LUCKY_NUMBER){
System.out.println(i);
count+=1;
}
}
System.out.println("Total count in lucky number("+LUCKY_NUMBER+") :"+count);

}

public static int sumValue(int number){
int sum = 0;
int digit = 0;
while(number > 0){
digit = number%10;
sum += digit;
number = number/10;
}
if (sum > 10) sum = sumValue(sum);
return sum;
}
}