You can use a dynamic approach using helper spaces
int sum=0; int a[n+1]; for(int i=1;i<=n;i++){ if(i%2!=0) a[i] = i; else a[i] = a[i/2]; } for(int i=1;i<=n;i++){ sum+=a[i]; } cout<<sum;
As and when the number is odd, the number itself will be the largest odd divisor, and [i] will keep its value, and when the number is even, then [number / 2] will be stored in [i], because for an even number the largest odd divisor of the number / 2 will be the largest odd divisor of a number.
It can also be resolved using three cases where the number is odd and then adds the else else number if the number is 2, then add 1 else if the number is equal, except for power 2, divide it by 2 until you get an odd value , and add this odd let down.
chetan kumar
source share