least calculation time to get 1, if n is odd,add or sub 1,if even divide by one.

least calculation time to get 1, if n is odd,add or sub 1,if even divide by one.

iteration solution:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <iostream>
using namespace std;
int function(unsigned int n)
{
if( n == 1 ) return 0;
if( (n % 2) == 0) return 1 + function(n/2);
return 2 + min(function(n-1)/2, function(n+1)/2);
}
int main()
{
for(int i = 1; i < 1000; i++)
{
printf("%d\n",function(i));
}
system("pause");
return 1;
}

你可能感兴趣的:(least calculation time to get 1, if n is odd,add or sub 1,if even divide by one.)