
#include <iostream>
using namespace std;
void fjzys(int n);
int main() { int n; cout << "输入一个数:"; cin >> n; cout << "质因数为:"; fjzys(n); }
void fjzys(int x) { //2,3,5,7 是质数 if(x == 2 || x == 3 || x == 5 || x ==7) cout << x << " "; else {
if(x % 2 == 0) { fjzys(x / 2); cout << 2 << " "; } else if(x % 3 == 0) { fjzys(x / 3); cout << 3 << " "; } else if(x % 5 == 0) { fjzys(x / 5); cout << 5 << " "; } else if(x % 7 == 0) { fjzys(x / 7); cout << 7 << " "; } else //如果无法被 2,3,5,7 整除,则直接判断为质数 cout << x << " "; } }
业务学习编程,始终感觉程序写得有点重复,算法不理想。
1 tlxxzj Mar 16, 2023 #include <iostream> void fjzys(int n) { if(n < 2) { return; } bool is_prime = true; int x = n; int m = n / 2; for(int i = 2; i < m; i++) { while(x % i == 0) { is_prime = false; std::cout<<i<<" "; x = x / i; } } if(is_prime) { std::cout<<n; } } int main() { fjzys(123456); return 0; } |
2 lapulasi Mar 16, 2023 Donald E.Knuth The Art of Computer Programming (vol.2) 4.5.4 Factoring into Primes |
3 tlxxzj Mar 16, 2023 太久没写 c++了 |
4 chenluo0429 Mar 16, 2023 via Android 143 表示有点难过 |
5 opengps Mar 16, 2023 //如果无法被 2,3,5,7 整除,则直接判断为质数 这个逻辑过于简单粗暴啊 ,正常不应该是穷举判断吗,输入 N ,遍历逐个判断除以 2,2 ,3 ,4 ,5 。。。。N-1 |
6 Oni Mar 16, 2023 via Android 这是在搞笑吗,初中数学老师应该没教给你质数是无法被 2,3,5,7 整除的整数吧? |
7 princelai Mar 16, 2023 |
8 loopinfor Mar 16, 2023 via Android 理论上需要穷举 2 到 N 开平方的所有数 |
9 opengps Mar 18, 2023 昨天随手写了个穷尽质数的代码,单线程现在跑了 4 个小时,495 万数据里找到了 34.5 万个质数了 |