2018年11月21日 星期三

itsa68 4算數移位相加

移位 例:000123 => 123000 可看成 (向左移*10 向右移*0.1)
原 1*10^2+2*10^1+3*10^0
果 1*10^5+2*10^4+3*10^3 = (1*10^2+2*10^1+3*10^0)*10^3
現在有一個數n,4位數,向右移3次後相加,可寫成
S = n+n*0.1+n*0.01+n*0.001
= n*(1+0.1+0.01+0.001)
= n*1.111
n = S / 1.111
算出來會是除了個位數的其他位數
因為有誤差所以要加回去(進位等)
跑0~20,加完後,判斷移位相加後的結果與S是否相同,即為所求a0


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include<iostream> 
#include<string> 
#include<cmath>
#include<iomanip>
using namespace std;

bool check(unsigned long long n, unsigned long long s, unsigned long long len)
{
 unsigned long long sum = 0;
 for (unsigned long long i = 0; i < len; i++)
 {
  sum += n;
  n /= 10;
 }
 if (sum - s == 0)
  return true;
 return false;
}

int main()
{
 int found;
 unsigned long long n, len, res;
 double div, fr;
 while (cin >> n)
 {
  len = (unsigned long long) (log10(n)) + 1;
  div = 1;
  fr = 0.1;
  found = 0;
  for (int i = 2; i <= len; i++)
  {
   div += fr;
   fr *= 0.1;
  }
  res = (unsigned long long)(n / div);
  for (int j = 0; j <= 20; j++)
  {
   if (check(res + j, n, len))
   {
    cout << res + j << endl;
    found = 1;
    break;
   }
  }
  if (found == 0)
   cout << -1 << endl;
 }
 return 0;
}

沒有留言:

張貼留言