I need to write a function that finds the multiplicative persistence of a given number.
The persistence is the number of products needed to get a single digit.
For example: (the Persistence for 76 would go like this)
76 = 42 (7*6) = 8 (4*2)
so the persistence is 2.
(for 57)
57 = 35 (5*7) = 15 (3*5) = 5 (1*5)
so the persistence is 3.
All I need is a value returning function for this.
In order to get the digits out alone I used modulus; however, I just got tied up somewhere.
Here's the start of what I was trying to do: (value is initialized earlier btw so that's not the problem)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int Persistent(int value)
{
int product = 1;
int n;
int i;
for (i=0; value > 0; i++)
{
n = product;
product = n*(value%10);
value = value / 10;
}
return i;
}
Obviously the code does not work, but I cannot seem to think of what I am suppose to do.
Thanks for that; however, I probably should have mentioned the rules to this. I am not allowed to use the string counters that you have implemented in your function.
I have to break down the numbers using binary-type tools.
For example:
value = 66
the number should pull 6 from 66 by using 66%10. Then, it multiplies that times the other 6, which is 66/10.
You now have 6*6 = 36. So the function then should pull the 6 through 36%10, and the 3 from 36/10.
You now have 3*6 = 18. So the function then should pull the 8 through 18%10, and the 1 from 18/10.
You now have 1*8 = 8.
The function will now give the persistent a value of 3, because it took three times to get a single digit.
I understand the logic to the situation; however, I am unable to figure out how to get the first new number (36) to multiply together.
int Persist( int value )
{
int count = 0; // number of times we multiplied all digits together
while( value > 9 ) // loop until it has only 1 digit remaining
{
int temp = 1;
do
{
temp *= (value % 10); // multiply 'temp' by the low digit
value /= 10; // drop the low digit
}while(value > 0); // loop until no digits remaining
value = temp; // 'temp' is all digits multiplied together. Put back in value
++count;
}
return count;
}
Thank you so much for the help guys. I'm using Disch's code.. it works perfect. Now for the rest of the program, but I'm going to try and get it on my own before asking. I was just confused with that function.