1059. Prime Factors (25)
題目如下:
Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p1^k1?* p2^k2?*…*pm^km.
Input Specification:
Each input file contains one test case which gives a positive integer N in the range of long int.
Output Specification:
Factor N in the format N = p1^k1?* p2^k2?*…*pm^km, where pi's are prime factors of N in increasing order, and the exponent ki?is the number of pi?-- hence when there is only one pi, ki?is 1 and must NOT be printed out.
Sample Input: 97532468 Sample Output: 97532468=2^2*11*17*101*1291題目的關鍵是設計出求下一個素數的函數,注意第一個素數是2。
定義當前素數prime,當前系數exp,初值prime=2,exp=0,如果輸入的值N能整除prime,則把exp++,并且N=N/prime,如果N=1,說明當前系數處理完畢,并且整個數也分解完畢,記錄當前prime和exp;如果N不能整除prime,則判斷exp是否為0,不為0說明對于這個prime被分解過exp次,也應該記錄prime和exp然后把exp置0,然后找到下一個prime繼續處理。
最后輸出所有記錄的值即可,用結構體和vector結合可以方便記錄prime和exp。
注意輸入的值為1時,應該特殊處理。
#include <iostream> #include <vector> #include <stdio.h>using namespace std;typedef unsigned long ulong;struct Node{ulong p;ulong k;Node(int _p, int _k) : p(_p), k(_k) {} };ulong nextPrime(ulong now){if(now <= 1) return 2;bool isPrime;while(1){now++;isPrime = true;for(ulong factor = 2; factor < now; factor++){if(now % 2 == 0) { isPrime = false; break; }}if(isPrime) return now;}}int main() {ulong prime = 2;vector<Node> nodes;ulong num;cin >> num;ulong exp = 0;ulong originNum = num;if(num == 1){cout << "1=1" << endl;return 0;}while(num != 1){if(num % prime == 0){num /= prime;exp++;if(num == 1) nodes.push_back(Node(prime,exp));}else{if(exp != 0){nodes.push_back(Node(prime,exp));exp = 0;}prime = nextPrime(prime);}}ulong p,k;printf("%ld=",originNum);for(int i = 0; i < nodes.size(); i++){p = nodes[i].p;k = nodes[i].k;if(k == 1) printf("%ld",p);else printf("%ld^%ld",p,k);if(i!=nodes.size() - 1) printf("*");}cout << endl;return 0; }
轉載于:https://www.cnblogs.com/aiwz/p/6154109.html
總結
以上是生活随笔為你收集整理的1059. Prime Factors (25)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: bzoj3456: 城市规划
- 下一篇: 如何做到长时间(4 个小时以上)精神专注