d085: 根號運算
Tags: factor
出處:https://zerojudge.tw/ShowProblem?problemid=d085
提交:https://zerojudge.tw/Submissions?problemid=d085&account=allllllan123456
問題:請輸出一個 int 整數開二次方根之後的結果,可能會有虛數。
解法:跟質因數分解差不多,就是要注意負數的處理,而且在除的時候因為是以質數的平方為單位,迴圈的終止條件也不能設為 1。
1#include <bits/stdc++.h>
2using namespace std;
3
4int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); // IO 優化
5 int n, out, in;
6 while (cin >> n) { int p = 2;
7 if (n==0 || n==1) { cout << n << '\n'; continue; }
8 in = abs(n); out = 1;
9 while (p * p <= in)
10 if (in % (p*p)) p++;
11 else out *= p, in /= p * p;
12 if (out != 1) cout << out;
13 if (in != 1) cout << "_/" << in;
14 if (n < 0) cout << "i";
15 cout << '\n';
16 }
17 return 0;
18}