算法学习->素数与合数小结

一、素数打表

/*
 *  素数筛选,查找出小于等于MAXN的素数并连续存到prime[1...n]中
 *  prime[0]存素数的个数,初始为0 
 */

#include
#include

const int MAXN = 100000;
int prime[MAXN + 1];
int vis[MAXN+1];
int cnt=0;

void getPrime() {
    memset(prime, 0, sizeof(prime));
    for (int i = 2; i <= MAXN; i++) {
        if (!prime[i]) {
            prime[++prime[0]] = i;
        }
        for (int j = 1; j <= prime[0] && prime[j] <= MAXN / i; j++) {
            prime[prime[j] * i] = 1;
            if (i % prime[j] == 0) {
                break;
            }
        }
    }
}
//这两个素数打表函数任选一个即可
void getPrime() {   //借助vis数组标记
    memset(prime,0,sizeof(prime));
    memset(vis,0,sizeof(vis));
    for(long long i=2; i<=MAXN; i++) {
        if(!vis[i]) {
            prime[++cnt]=i;
        }
        for(long long j=i*i; j<=MAXN; j+=i) {
            vis[j]=1;
        }
    }
}
int main() {
    //相关操作......

    return 0;
}

二、合数分解

#include
#include

const int MAXN = 10000;
int prime[MAXN + 1];
long long factor[100][2];
int fatCnt;

//  获取素数
void getPrime() {
    memset(prime, 0, sizeof(prime));
    for (int i = 2; i <= MAXN; i++) {
        if (!prime[i]) {
            prime[++prime[0]] = i;
        }
        for (int j = 1; j <= prime[0] && prime[j] <= MAXN / i; j++) {
            prime[prime[j] * i] = 1;
            if (i % prime[j] == 0) {
                break;
            }
        }
    }
    return ;
}

//  合数分解
int getFactors(long long x) {
    fatCnt = 0;
    long long tmp = x;
    for (int i = 1; prime[i] <= tmp / prime[i]; i++) {
        factor[fatCnt][1] = 0;
        if (tmp % prime[i] == 0) {
            factor[fatCnt][0] = prime[i];
            while (tmp % prime[i] == 0) {
                factor[fatCnt][1]++;
                tmp /= prime[i];
            }
            fatCnt++;
        }
    }
    if (tmp != 1) {
        factor[fatCnt][0] = tmp;
        factor[fatCnt++][1] = 1;
    }
    return fatCnt;
}
int main() {
    //相关操作......

    return 0;
}

你可能感兴趣的:(素数与合数)