【发布时间】:2021-08-29 12:54:56
【问题描述】:
给定一个范围 [ L , R ](包括两者),我必须告诉找到给定范围内两个素数之间的最大差异。给定范围可能有三个答案。
如果给定范围内只有一个不同的素数,那么这种情况下的最大差值为 0。
如果给定范围内没有素数,那么这种情况下的输出将为 -1。
例子:
Range: [ 1, 10 ]
The maximum difference between the prime numbers in the given range is 5.
Difference = 7 - 2 = 5
Range: [ 5, 5 ]
There is only one distinct prime number so the maximum difference would be 0.
Range: [ 8 , 10 ]
There is no prime number in the given range so the output for the given range would be -1.
输入格式 第一行输入包含测试用例的数量,T
接下来的 T 行每行由两个空格分隔的整数 L 和 R 组成
约束 1
2
这是我的代码:
#include <stdio.h>
int isprime(int n)
{
int i,c=0;
for(i=1;i<n;i++)
{
if(n%i==0)
c++;
}
if(c==1)
return 1;
else
return 0;
}
int main()
{
int t; //testnumber
scanf("%d",&t);
for(int k=0;k<t;k++)
{
int l,r; //l=low or floor, r = highest range or ceiling;[l,r]
scanf("%d%d",&l,&r);
int n = r-l; //difference in range
int a[n];
int j=0;
for(int i=l;i<=r;i++)
{
if(isprime(i)==1)
{
a[j] = i;
j++;
}
}
int d = a[j-1]-a[0];
if(j==0)
printf("%d\n",-1);
else
printf("%d\n",d);
}
return 0;
}
【问题讨论】:
-
让代码高效运行实际上是任务的一部分。您提出的第一个想法通常不足以解决问题,其中一部分是时间限制。但只是说,您的
isprime循环只需要测试 odd 除数,即n的平方根。它可以打破你找到一个因素的第一次。它不需要完成迭代。您可能会考虑的另一件事是制作一个素数列表,这样您就不必不断重复相同的计算。 -
我投票结束这个问题,因为它属于:codereview.stackexchange.com
-
您要学习的东西太多了。首先读取eratosthenes的筛子,然后对素数数组中的范围进行二分搜索。
-
从isprime开始godbolt.org/z/hznbTcj5q
标签: c time time-complexity