如何优化这个c程序来找到一个数字的质因数分解
How to optimize this c program to find the prime factorisation of a number
我已经为一个数字的质因数分解写了一个代码,但我不知道如何优化它以获得更大的数字更好的结果,有人知道吗?
#include<stdio.h>
int prime(int p, int q, int r);
int main(){
int n,c=0;
scanf("%d",&n);
for(int j=2;j<=n;j++){
int t=0;
for(int i=1;i<=j;i++){
if(j%i==0){
t++;
}
}
if(t==2){ //check whether J is prime or not
// printf(" %d ",j);
c=prime(n,j,0); //check whether j has any factors with N
if(c!=0){
printf(" %d ",j);
printf(" %d n",c);
}
}
}
return 0;
}
int prime(int p,int q,int r){
if(p%q==0){
r++;
prime(p/q,q,r);
}
else{
return r;
}
}
你的代码相当于
#include <stdio.h>
int main(){
int n;
scanf("%d", &n);
for(int j=2; j <= n; j++) { // for each j in 2..n,
int t=0;
for(int i=1; i<=j; i++) { // count j's divisors
if(j%i==0) { // among 1..j
t++;
}
}
if( t==2 ){ // if j is prime: NB!
int c=0, nn=n;
while( nn%j==0 ) { // count multiplicity of j
c++; // as divisor of n, and
nn /= j;
}
if( c!=0 ){ // report a prime divisor and
printf(" %d %d n", j, c); // its multiplicity
}
}
}
return 0;
}
但实际上需要的是:
int main(){
int n, c=0;
scanf("%d", &n);
for(int j=2; j <= n; j++) { // for each j in 2..n,
int c=0;
while( n%j==0 ) { // if j divides n
c++; // count its multiplicity
n /= j; // while dividing it out of n
} // NB! changing the `n` NB!
// which guarantees j is prime
if( c!=0 ){ // when c != 0
printf(" %d %d n", j, c);
}
}
return 0;
}
,所以最后一个重要的优化是
int main(){
int n, c=0;
scanf("%d", &n);
for(int j=2; j*j <= n; j++) { // here
int c=0;
while( n%j==0 ) {
c++;
n /= j;
}
if(c!=0){
printf(" %d %d n", j, c);
}
}
if(n>1) { // and here
printf(" %d %d n", n, 1);
}
return 0;
}
接下来,你可以尝试在主循环中找到一种方法将j
增加2,以使其范围仅为奇数,因为2之上的偶数不可能是素数。
#include <stdio.h>
//function to check for prime numbers (return '1' if prime ,else return '0').
int checkprime(int pr)
{
if ((pr==2)||(pr==3))
{
return (1);
}
else
{
for (int i = 3; i <pr; i=i+2)
{
if (pr%i==0)
{
return (0);
}
}
return 1;
}
}
//function to print the prime factors..
int primefactors(int num)
{
int temp;
temp=num;
while(temp!=0 && temp%2==0)
{
if (temp%2==0)
{
printf("2 ");
temp/=2;
}
}
for (int k =3; k <=temp&& temp!=0 ; k=k+2)
{
if (checkprime(k)==1)
{
while ((temp!=0) && (temp%k==0))
{
printf("%d ",k);
temp/=k;
}
}
}
}
int main()
{
int a;
a=65;
if (a>1)
{
primefactors(a);
}
else
{
printf("variable 'a' should be greater 1!");
}
}
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 通过递归进行因子分解
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么在这个分解的 std::string dtor 中有一个锁定的 xadd 指令?
- 在分解的 QR 上应用一个大矩阵
- 如何使用字符串数组来分解一个数字的单个数字
- 在 Javascript 中分解一个数字
- 如何在c++中将计算分解为两个double和一个char
- 确定可以分解为素数 {2,3,5,7} 的下一个最高数
- 我能否对这C++代码的每一行中发生的事情有一个分解的解释
- 将一个 2 字节整数转换并分解为 2 个不同的 uchar,C++具有 endianess 兼容性
- C++模板:一个按类列出的列表,如何分解代码
- 需要一个使用gsl-LU分解获得平方矩阵逆的示例代码
- 将一个循环分解为两个循环的性能
- 分解一个简单的C++程序
- 构造一个c++linux程序.何时分解单独的文件与单独的程序
- 将一个大文件分解为一个DLL的陷阱
- 给定一个素数列表和一个因数分解模式,如何构造其因数分解符合给定模式的所有数
- 如何优化这个c程序来找到一个数字的质因数分解
- 试图创建一个程序来读取用户输入,然后将数组分解为单独的单词,我的指针都有效吗