算法笔记 Day 4
1013 数素数 (20分)
令 Pi 表示第 i 个素数。现任给两个正整数 M≤N≤104 ,请输出 PM 到 PN 的所有素数。
输入格式:
输入在一行中给出 M 和 N,其间以空格分隔。
输出格式:
输出从 PM 到 PN 的所有素数,每 10 个数字占 1 行,其间以空格分隔,但行末不得有多余空格。
输入样例:
5 27
输出样例:
11 13 17 19 23 29 31 37 41 43
47 53 59 61 67 71 73 79 83 89
97 101 103
Code:
#include<stdio.h>
#include<string.h>
const int maxn = 1000001;
int prime[maxn];
int num = 0;
bool judge[maxn] = {0};
void Find_Prime(int n){
int i;
for(i=2;i<maxn;i++){
if(judge[i] == false){
prime[num++] = i;
if(num >=n){
break;
}
for(int j=i+i;j<maxn;j+=i){
judge[j] = true;
}
}
}
}
int main(void){
int m,n;
scanf("%d %d",&m,&n);
Find_Prime(n);
int i;
int count = 0;
for(i=m-1;i<n;i++){
printf("%d",prime[i]);
count++;
if(count % 10 == 0){
printf("\n");
}
else if(i == n-1){
return 0;
}
else{
printf(" ");
}
}
}
1059 Prime Factors (25分)
Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p1 k1×p2 k2×⋯×pm km
Input Specification:
Each input file contains one test case which gives a positive integer N in the range of long int.
Output Specification:
Factor N in the format N = p1 k1×p2 k2×⋯×pm km, where pi 's are prime factors of N in increasing order, and the exponent ki is the number of pi – hence when there is only one pi, ki is 1 and must NOT be printed out.
Sample Input:
97532468
Sample Output:
97532468=2^2*11*17*101*1291
Code:
#include<stdio.h>
#include<string.h>
#include<math.h>
const int maxn = 100010;
bool judge[maxn] = {0};
int num[maxn];
int n = 0;
struct factor{
int x,cnt;
}fac[10];
bool isprime(int n){
if(n == 2){
return true;
}
for(int i = 2;i<sqrt(n);i++){
if(n % i == 0){
return false;
}
}
return true;
}
void Find_Prime(){
for(int i = 2;i<maxn;i++){
if(judge[i] == false){
num[n++] = i;
for(int j = i+i;j<maxn;j+=i){
judge[j] = true;
}
}
}
}
int main(void){
int i;
int count = 0;
Find_Prime();
long long N;
scanf("%lld",&N);
long long M = N;
if((N == 1) || (isprime(N)== true)){
printf("%d=%d",N,N);
return 0;
}
for(i=0;i<n;i++){
if(N % num[i] == 0){
fac[count].x = num[i];
fac[count].cnt = 0;
while(N % num[i] == 0){
N /= num[i];
fac[count].cnt += 1;
}
count++;
if(N == 1){
break;
}
}
}
printf("%d=",M);
int flag = 0;
for(i=0;i<count;i++){
if(fac[i].cnt == 1){
printf("%d",fac[i].x);
flag = 1;
}
else if(fac[i].cnt != 0){
printf("%d^%d",fac[i].x,fac[i].cnt);
flag = 1;
}
if((i != count - 1) && (flag == 1)){
printf("*");
flag = 0;
}
}
return 0;
}
上一篇: 媳妇是二货,老公也不弱
推荐阅读
-
算法学习笔记 二叉树和图遍历—深搜 DFS 与广搜 BFS
-
韩顺平_PHP软件工程师玩转算法公开课(第一季)01_算法重要性_五子棋算法_汉诺塔_回溯算法_学习笔记_源代码图解_PPT文档整理
-
算法的时间复杂度和空间复杂度笔记
-
【莫烦强化学习】视频笔记(二)3.Q_Learning算法实现走迷宫
-
PHP读书笔记(4)-运算符,php读书笔记运算符_PHP教程
-
bootstrap学习笔记(4) - tuohaibei
-
JavaEE基础day02 1.定义Java中的变量 四类八种 2.变量定义和使用的注意事项 3.数据类型的转换、强制数据类型转换4.算数运算符、比较运算符、逻辑运算符、赋值运算符、三元运算符
-
OpenGL学习笔记4-Hello Triangle
-
Python学习笔记Day2
-
SqlServer 2005 T-SQL Query 学习笔记(4)