分解质因数的程序,麻烦大家帮忙优化下。

2023-03-16 09:48:02 +08:00
 windbadboy

#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 << " ";

    }

}

业务学习编程,始终感觉程序写得有点重复,算法不理想。

1290 次点击
所在节点    编程
9 条回复
tlxxzj
2023-03-16 10:17:08 +08:00
#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;
}
lapulasi
2023-03-16 10:17:21 +08:00
Donald E.Knuth The Art of Computer Programming (vol.2) 4.5.4 Factoring into Primes
tlxxzj
2023-03-16 10:17:28 +08:00
太久没写 c++了
chenluo0429
2023-03-16 11:46:17 +08:00
143 表示有点难过
opengps
2023-03-16 11:49:44 +08:00
//如果无法被 2,3,5,7 整除,则直接判断为质数
这个逻辑过于简单粗暴啊 ,正常不应该是穷举判断吗,输入 N ,遍历逐个判断除以 2,2 ,3 ,4 ,5 。。。。N-1
1234rty
2023-03-16 12:00:06 +08:00
这是在搞笑吗,初中数学老师应该没教给你质数是无法被 2,3,5,7 整除的整数吧?
princelai
2023-03-16 12:54:16 +08:00
我虽然不会写 C,但可以让 chatgpt 帮你写一个你作为参考

loopinfor
2023-03-16 13:30:12 +08:00
理论上需要穷举 2 到 N 开平方的所有数
opengps
2023-03-18 17:22:25 +08:00
昨天随手写了个穷尽质数的代码,单线程现在跑了 4 个小时,495 万数据里找到了 34.5 万个质数了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/924411

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX