Find a number in minimum steps | Python3 program to Find a number in minimum steps ; Steps sequence ; Current sum ; Sign of the number ; Basic steps required to get sum >= required value . ; If we have reached ahead to destination . ; If the last step was an odd number , then it has following mechanism for negating a particular number and decreasing the sum to required number Also note that it may require 1 more step in order to reach the sum . ; If the current time instance is even and sum is odd than it takes 2 more steps and few negations in previous elements to reach there . ; Driver code
def find ( n ) : NEW_LINE INDENT ans = [ ] NEW_LINE Sum = 0 NEW_LINE i = 0 NEW_LINE sign = 0 NEW_LINE if ( n >= 0 ) : NEW_LINE INDENT sign = 1 NEW_LINE DEDENT else : NEW_LINE INDENT sign = - 1 NEW_LINE DEDENT n = abs ( n ) NEW_LINE i = 1 NEW_LINE while ( Sum < n ) : NEW_LINE INDENT ans . append ( sign * i ) NEW_LINE Sum += i NEW_LINE i += 1 NEW_LINE DEDENT if ( Sum > sign * n ) : NEW_LINE INDENT if ( i % 2 != 0 ) : NEW_LINE INDENT Sum -= n NEW_LINE if ( Sum % 2 != 0 ) : NEW_LINE INDENT ans . append ( sign * i ) NEW_LINE Sum += i NEW_LINE i += 1 NEW_LINE DEDENT ans [ int ( Sum / 2 ) - 1 ] *= - 1 NEW_LINE DEDENT else : NEW_LINE INDENT Sum -= n NEW_LINE if ( Sum % 2 != 0 ) : NEW_LINE INDENT Sum -= 1 NEW_LINE ans . append ( sign * i ) NEW_LINE ans . append ( sign * - 1 * ( i + 1 ) ) NEW_LINE DEDENT ans [ int ( ( sum / 2 ) ) - 1 ] *= - 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT n = 20 NEW_LINE if ( n == 0 ) : NEW_LINE INDENT print ( " Minimum number of Steps : 0 Step sequence : 0 " ) NEW_LINE DEDENT else : NEW_LINE INDENT a = find ( n ) NEW_LINE print ( " Minimum ▁ number ▁ of ▁ Steps : " , len ( a ) ) NEW_LINE print ( " Step ▁ sequence : " ) NEW_LINE print ( * a , sep = " ▁ " ) NEW_LINE DEDENT