素因子分解 前言 这是一道在pta上的题目,成功地卡了我几个小时……我第一种的解法超时,好不容易写出了第二种复杂的解法终于把题目过了,然后回头一看同学的做法简单多了,顿时感觉我是小丑……好好好,记录一下。
题目 给定某个正整数 N ,求其素因子分解结果,即给出其因式分解表达式 N=p1^k1*p2^k2*…*pm^km
。
输入格式: 输入long int范围内的正整数 N。
输出格式: 按给定格式输出N的素因式分解表达式,即 N=p1^k1*p2^k2*…*pm^km
,其中pi
为素因子并要求由小到大输出,指数ki
为pi
的个数;当ki
为1即因子pi
只有一个时不输出ki
。
输入样例:
输出样例:
代码实现 啥也不想解释,代码自己看吧┭┮﹏┭┮
我的小丑做法 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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 #include <bits/stdc++.h> using namespace std;typedef long long LL;struct sys { LL num; LL ans=0 ; }; bool operator <(const sys& a, const sys& b) { return a.num < b.num; } set<sys> arr; LL n,x=0 ; void add (LL num) { sys temp; temp.num = num, temp.ans = 1 ; set<sys>::iterator ops = arr.lower_bound (temp); if (ops == arr.end ()) arr.insert (temp); else { temp.ans += ops->ans; arr.erase (ops); arr.insert (temp); } } bool is_prime (LL num) { LL temp = sqrt (num); for (LL i=2 ; i <= temp; i++) if (num % i == 0 ) return false ; return true ; } int main () { cin >> n; if (n == 1 ) { cout << "1=1" ; return 0 ; } cout << n << "=" ; while (!is_prime (n)) { for (LL i=n / 2 ; i >= 2 ; i--) { if (n % i == 0 ) { LL t = n / i; add (t); n = i; break ; } } } add (n); LL flag = 0 ; for (set<sys>::iterator it = arr.begin (); it != arr.end (); it++) { if (flag) cout << "*" ; cout << it->num; if (it->ans != 1 ) cout << "^" << it->ans; flag = 1 ; } return 0 ; }
同学优雅的做法 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 51 #include <stdio.h> #define ll long long int isprime (ll a) { for (ll i = 2 ; i <= a / i ; i++){ if (a % i == 0 ) return 0 ; } return 1 ; } int ans[10000 ];int ans_cnt[10000 ];int main () { ll N; scanf ("%lld" ,&N); int is_can = 0 ; ll temp = N; for (ll i = 2 ; i <= N / i && temp!=1 ; i++){ if (!isprime (i)) continue ; ll cnt = 0 ; if (temp%i==0 ){ is_can++; ans[is_can] = i; while (temp%i==0 ){ cnt++; temp /= i; } ans_cnt[is_can] = cnt; } } printf ("%lld=" ,N); if (is_can==0 ) printf ("%lld" ,N); else for (ll i = 1 ; i <= is_can ; i++){ if (ans_cnt[i]==1 ) { printf ("%d" ,ans[i]); } else printf ("%d^%d" ,ans[i],ans_cnt[i]); if (i != is_can) printf ("*" ); } }
反思 做题找不到好的解法的时候还是要多思考,自己多模拟几种做法,思维开阔一点,要找到合适的解法尽量不要写复杂了。