数论问题
素数问题
计算几何
1 素数也就是我们所说的质数,讲到质数就要讲合数,合数就是与质数相对立的,有多个因子,合数有一个性质:所以合数的因子不会大于sqrt(n)(这个很重要,可以省略很多次循环),我们可以用这个求出小于等于n的素数。
num =0 ;
bool isprime[1000];
int prime[1000];
memset(isprime,1,sizeof(isprime));//全部为真
for(int i=2;i<=sqrt(n);i++){
if(ispriem[i]){
for(int j=i+1;j<n;j++){
if(j%i==0){
isprime[j]=0;
}
}
}
}
for(int i=2;i<n;i++){
if(isprime[i]){
prime[num++]=i;
}
}
这里采用的是筛选法isprime是用来判断是否是素数,然后再通过prime将素数保存下来。
题目链接:
链接: prime gap.
我的代码:
#include<stdio.h>
#include<math.h>
int main()
{
int k,n,m,j;
while(scanf("%d",&k)){
int flag=1;
for(int i=k;i>2;i--){//因为这里的数据不大,所以没有用筛选法,采用的是一般法
for( j=2;j<sqrt(i);j++){
if(i%j==0){
break;
}
}
if(j>sqrt(i)){//判断出素数就弹出
flag=0;
m=i;
break;
}
}
if(flag){
printf("0\n");
continue;
}
for(int i=k;1;i++){
for( j=2;j<sqrt(i);j++){
if(i%j==0){
break;
}
}
if(j>sqrt(i)){
n=i;
break;
}
}
printf("%d\n",n-m);
}
return 0;
}
这题比较简单,考的是双向思维。做素数问题,双向思维一定要有。
接下来这题就运用了筛选法
题目1259. Sum of Consecutive Primes
Description
Some positive integers can be represented by a sum of one or more consecutive prime numbers. How many such representations does a given positive integer have? For example, the integer 53 has two representations 5 + 7 + 11 + 13 + 17 and 53. The integer 41 has three representations 2+3+5+7+11+13, 11+13+17, and 41. The integer 3 has only one representation, which is 3. The integer 20 has no such representations. Note that summands must be consecutive prime
numbers, so neither 7 + 13 nor 3 + 5 + 5 + 7 is a valid representation for the integer 20.
Your mission is to write a program that reports the number of representations for the given positive integer.
Input
The input is a sequence of positive integers each in a separate line. The integers are between 2 and 10 000, inclusive. The end of the input is indicated by a zero.
Output
The output should be composed of lines each corresponding to an input line except the last zero. An output line includes the number of representations for the input integer as the sum of one or more consecutive prime numbers. No other characters should be inserted in the output.
Sample Input
2
3
17
41
20
666
12
53
0
Sample Output
1
1
2
3
0
0
1
2
求连续素数和为某数的情况数,筛选法建立素数,两层循环实现。
我的代码:
#include<stdio.h>
#include<math.h>
#include<string.h>
#define max 10001
bool isprime[max];
int prime[max],prime_num;
int getprime()
{
memset(isprime,1,sizeof(isprime));
for(int i=2;i<sqrt(max);i++){
if(isprime[i]){
for(int j=i+1;j<max;j++){
if(j%i==0){
isprime[j]=0;
}
}
}
}
prime_num=0;
for(int i=2;i<max;i++){
if(isprime[i]){
prime[prime_num++]=i;
}
}
}
int main()
{
getprime();
int k;
while(scanf("%d",&k)){
if(k<2||k==0||k>10000){
break;
}
int ans=0;
for(int i=0;i<prime_num;i++){
int sum=0;
int j=i;//以第i个为开始点,开始进行顺序相加
while(sum<k){
sum+=prime[j++];
}
if(sum==k){
++ans;
}
}
printf("%d\n",ans);
}
return 0;
}
具体代码还需慢慢品尝,才能明白这筛选法的美味;
本期就到这里,谢谢大家!!!