日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

1059. Prime Factors (25)

發布時間:2024/4/17 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。