# https://yukicoder.me/submissions/987943 ベースの実装
if K == 1
  $0=1134903170
  $1=701408733
  $2=1
  $3=701408733
  $4=433494437
  $5=1
  $8=43
end
if K >= 2
$0=1
$1=1
$2=1
$8=0
while $0 <= N
  $3=$0
  $4=$1
  $5=$2
  $0=K*$4
  $1=$0-$4
  $2=$1
  $0=$0+$3
  $1=$1+$3
  $2=$2+$5
  $8=$8+1
end
end

$6=N-1
$7=2
$9=1
while $8 > 0
  if $7 <= 1
    if $6 < $0
      $7=3
    end
    if $6 >= $0
      $6=$6-$0
      $9=$9+$0
      $9=$9+$3
    end
  end
  if $7 == 2
    if $6 < $2
      $7=5
    end
    if $6 >= $2
      $6=$6-$2
      $9=$9+$2
      $9=$9+$5
    end
  end
  if $7 <= 2
    $7=$6/$1
    $6=$6%$1
    $1=$1+$4
    $7=$7*$1
    $9=$9+$7
    $7=4
  end
  $7=$7-3
  $8=$8-1
  $0=$3
  $1=$4
  $2=$5
  
  $4=$0-$1
  $3=$4*K
  $3=$0-$3
  $5=$4*K
  $5=$5-$4
  $5=$2-$5
end

$9=$9+$6

$0=$9-N
$2=N*N        # $2,$3 := (N*N),(K*N);
$3=K*N
if M == 0     # if M==0:
  $4=$0*$0    #   $4 := K*N*$0+N+$0+$0*$0;
  $4=$4+$0
  $4=$4+N
  $3=$3*$0
  $4=$4+$3
  $5=N-$0     #   $5 := N*N+(2*(N-$0)-1)/K;
  $5=$5*2
  $5=$5-1
  $5=$5/K
  $5=$5+$2
  if $4 > $5  #   if $4>$5:
    $0=$0-1   #     $0 := $0 - 1;
  end         #   end
end           # end
if M > 1      # if M>1:
  $6=$0+1     #   $6 := $0+1;
  $1=M-1      #   $1 := M-1;
  $3=$3*$6    #   $4 := K*N*$6+$6*$6+(2*(N-$6)+$1)*$1/K;
  $4=N-$6
  $4=$4*2
  $4=$4+$1
  $4=$4*$1
  $4=$4/K
  $4=$4+$3
  $3=$6*$6
  $4=$4+$3
  $5=N+$6     #   $5 := N*N+$1*(N+$6);
  $5=$5*$1
  $5=$5+$2
  if $4 < $5  #   if $4<$5:
    $0=$0+1   #     $0 := $0+1;
  end         #   end
end           # end
$0=$0+N       # return ($0+N);
return $0