Sunday, January 04, 2015

Java Program For Finding Multiplicative Persistence Of A Given Number


Hey friends how are you? Today after a long time i am sharing this post with all of you.I hope you all are good and healthy..:)


Today i am sharing a java program. In this program we have one function MultiplicativePersistence(num) that take one parameter num  which is positive integer and return its multiplicative persistence which is the number of times you must multiply the digits in num until you reach a single digit.

For example:-

If num is 39 then this program should return 3 because 3 * 9 = 27  and 2 * 7 =14 and finally 1 * 4 = 4 and we get 4 that is single digit.So here it is clear that we need 3 steps to get single digit (4)  from given number (39). 


Java Code


import java.util.Scanner;

class Function {

int MultiplicativePersistence(int num) {

        int count = 0, sum = 1, i;
Boolean r = true;
String string=null;
if (num < 10) {
return 0;

} else {

                         //Convert Integer to String by Integer.ToString()
string = Integer.toString(num);
while (r) {

for (i = 0; i < string.length() - 1; i++) {
                                         
                                         //Integer.parseInt() function convert String to Integer
sum = sum * Integer.parseInt(string.substring(i, i + 1));
}
   
                            
                                         //Integer.parseInt() function convert String to Integer
sum = sum * Integer.parseInt(string.substring(i, string.length()));

if (sum < 10) {
r = false;
} else {
                                        //Convert Integer to String by Integer.ToString()
string = Integer.toString(sum);
sum = 1;
}
count++;
}
}

return count;

}

public static void main(String[] args) {

//Scanner is class that used for taking input from user

Scanner s = new Scanner(System.in);
Function c = new Function();
               // nextInt() is method in Scanner class that is used to take integer
System.out.print(c.MultiplicativePersistence(s.nextInt()));
}

}           


Output

I run this code in Eclipse Juno.When I enter 39 as input then i get 3 as output.



Thanks friends , So if you like this post or you want to give any suggestion then please comment below.

1 comment:

Please Give Me Your Views

Popular Posts