後面第4點“解決思路”說了什麽?
授人以渔,不授人以鱼。
#include<stdio.h> void ff(int n,int a[],int l) {//分解质因数,质因数都存储在数组a中 int i; for(i=2;(i*i<=n)&&(n%i);i++); if(i==1||i*i>n)a[l]=n; else { a[l]=i; ff(n/i,a,++l); } } int main() { int i,j,k,n,a[100]={0}; printf("输入需分解的数(任意字符退出):"); while(scanf("%d",&n)) { for(i=0;i<100;i++)a[i]=0; ff(n,a,0); printf("%d=",n); for(i=0,j=0,k=1;i<100;i++) { if(a[i]!=j) { if(j&&k>1)printf("^%d",k); if(i&&a[i])printf("*"); if(a[i])printf("%d",a[i]); j=a[i]; k=1; } else k++; if(!a[i])break; //改为直到型循环可能更直接 } printf("\n"); printf("输入需分解的数(任意字符退出):"); } return 0; }
#include<stdio.h> void ff(int n,int a[],int l) {//分解质因数,质因数都存储在数组a中 int i,j; j=2; if(l)j=a[l-1]; //最小因子从上次筛选获得,可减少时间复杂度 for(i=j;(i*i<=n)&&(n%i);i++); if(i==1||i*i>n)a[l]=n; else { a[l]=i; ff(n/i,a,++l); } } int main() { int i,j,k,n,a[100]={0}; printf("输入需分解的数(任意字符退出):"); while(scanf("%d",&n)) { for(i=0;i<100;i++)a[i]=0; ff(n,a,0); printf("%d=",n); for(i=0,j=0,k=1;i<100;i++) { if(a[i]!=j) { if(j&&k>1)printf("^%d",k); if(i&&a[i])printf("*"); if(a[i])printf("%d",a[i]); j=a[i]; k=1; } else k++; if(!a[i])break; //改为直到型循环可能更直接 } printf("\n"); printf("输入需分解的数(任意字符退出):"); } return 0; }
#include <cstdio> #include <cstdlib> #include <vector> #include <conio.h> // 項結構 struct Item { unsigned short p; // 素因子 size_t k; // 指數 Item(unsigned short p, size_t k = 0) { this->p = p; this->k = k; } bool operator==(const Item& item) { return (this->p == item.p) && (this->k == item.k); } bool operator!=(const Item& item) { return (this->p != item.p) || (this->k != item.k); } }; // 裝入素數表 const std::vector<unsigned short> Load_PrimeList(const char* filename) { std::vector<unsigned short> list; FILE* file; if (fopen_s(&file, filename, "rb") == 0) { unsigned short i; while (fread(&i, sizeof(i), 1, file) == 1) { list.push_back(i); } fclose(file); } return list; } int main(void) { const std::vector<unsigned short> prime_list(Load_PrimeList("Prime.DAT")); if (prime_list.empty()) { return EXIT_FAILURE; } long int n_array[] = { 1024, 1323, 97532468, 1, 3, 65521 * 65534 }; for (unsigned long int n : n_array) { printf_s("%u = ", n); std::vector<Item> items; std::vector<unsigned short>::const_iterator it = prime_list.cbegin(); if (n != 1) { while (n != 1) { if (n % *it == 0) { if (items.empty() || (items.back().p != *it)) { items.push_back(Item(*it)); } if (items.back().p == *it) { ++items.back().k; } n /= *it; } else { ++it; } } for (Item item : items) { printf_s("%u", item.p); if (item.k > 1) { printf_s("^%u", item.k); } if (item != items.back()) { printf_s(" * "); } } } else { printf_s("%u", n); } putchar('\n'); } printf_s("\nPress any key to continue..."); _getch(); return EXIT_SUCCESS; }
[此贴子已经被作者于2015-11-5 22:54编辑过]