0
0

yukicoder No.56 消費税 解説

Posted at

問題文

解説

まず、答えは$\lfloor D*\frac{100+P}{100}\rfloor$となる($\lfloor x\rfloor$は$x$以下の最大の整数のこと)。
ただし、$\frac{100+P}{100}$をそのまま小数にして計算すると、精度落ちでWAになってしまう。
よって、すべて整数で計算する工夫が必要。
$\lfloor D*\frac{100+P}{100}\rfloor$は$\lfloor D*(100+P)\div 100\rfloor$と同値なので、先に$D*(100+P)$を求めてから100で割る(切り捨て)というのがいい方法。
こういう最後に整数で割る計算の時の誤差が不安な場合、私は次のような関数を使っている。

using ll=long long;
ll downfloor(ll x,ll m) {
  ll r=(x%m+m)%m;
  return (x-r)/m;
}

これは確実に正しい計算ができるので、最後は上記の計算式に従って解けばよい。
$D=10^7,P=100$みたいな大きな数字だと、$D*(100+P)\geqq 2^{31}$と32bitをオーバーするので、long long型を使うこと。

C++での解答例

#include <bits/stdc++.h>
using namespace std;
using ll=long long;

ll downfloor(ll x,ll m){
  //floor(x/m)を正確に求める
  ll r=(x%m+m)%m;
  return (x-r)/m;
}

int main(){
  ll D,P;cin>>D>>P;
  cout<<downfloor(D*(100+P),100LL)<<endl;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0