The question asks me to find the greatest power devisor of (number, d) I found that the function will be like that:
number % d^x ==0
I’ve done so far using for loop:
int gratestDevisor(int num, int d){ int p = 0; for(int i=0; i<=num; i++){ //num % d^i ==0 if( (num % (int)pow(d,i))==0 ) p=i; } return p; }
I’ve tried so much converting my code to recursion, I can’t imagine how to do it and I’m totally confused with recursion. could you give me a tip please, I’m not asking you to solve it for me, just some tip on how to convert it to recursion would be fine.
Answer
Here is a simple method with recursion. If d
divides num
, you simply have to add 1 to the count, and divide num
by d
.
#include <stdio.h> int greatestDevisor(int num, int d){ if (num%d) return 0; return 1 + greatestDevisor (num/d, d); } int main() { int num = 48; int d = 2; int ans = greatestDevisor (num, d); printf ("%dn", ans); return 0; }