a010: 因數分解
#include
#include
int main ()
{
int n, nn;
while (scanf ("%d", &n) == 1) {
int last = -1;
int cnt=1;
nn = sqrt(n);
while (!(n % 2)) {
n >>= 1;
if (last != 2) {
printf ("2");
last = 2;
cnt = 1;
} else cnt++;
}
if (cnt > 1) {
printf ("^%d", cnt);
cnt = 1;
}
for (int i = 3; i <= nn;) {
if (n % i == 0) {
n /= i;
if (last != i) {
if (cnt > 1) printf ("^%d * %d", cnt, i);
else {
if (last <= 0) printf ("%d", i);
else printf (" * %d", i);
}
cnt = 1;
} else cnt++;
last = i;
} else i += 2;
}
if (cnt > 1) {
if (n > 1)
printf ("^%d * %d\n", cnt, n);
else
printf ("^%d\n", cnt);
} else if (n > 1) {
if (last <= 0)
printf ("%d\n", n);
else
printf (" * %d\n", n);
} else puts("");
}
return 0;
}
上面的速度應該是比較快的,底下還有一個比較簡明的版本
#include
#include
0 意見:
張貼留言