OJ Prime Gap

目录

1.题目

2.中文翻译

3.题意

4.代码

5.知识点

range的倒序处理:


1.题目

Prime Gap

Description

        The sequence of n − 1 consecutive composite numbers (positive integers that are not prime and not equal to 1) lying between two successive prime numbers p and p + n is called a prime gap of length n. For example, ‹24, 25, 26, 27, 28› between 23 and 29 is a prime gap of length 6.

        Your mission is to write a program to calculate, for a given positive integer k, the length of the prime gap that contains k. For convenience, the length is considered 0 in case no prime gap contains k.

Input

        The input is a sequence of lines each of which contains a single positive integer. Each positive integer is greater than 1 and less than or equal to the 100000th prime number, which is 1299709. The end of the input is indicated by a line containing a single zero.

Output

        The output should be composed of lines each of which contains a single non-negative integer. It is the length of the prime gap that contains the corresponding positive integer in the input if it is a composite number, or 0 otherwise. No other characters should occur in the output.

Sample Input

10
11
27
2
492170
0

Sample Output

4
0
6
0
114

2.中文翻译

 素数间隙

题目描述:

        位于两个连续素数p和p+n之间的n−1个连续复数(非素数且不等于1的正整数)的序列称为长度为n的素数间隙。例如,在23和29之间的›24、25、26、27、28›是长度为6的主间隙。

        你的任务是编写一个程序来计算,对于给定的正整数k,包含k的素数间隙的长度。为了方便起见,在没有素数间隙包含k的情况下,长度被认为是0

输入:

        输入是一系列行,每行包含一个正整数。每个正整数都大于1,并且小于或等于第100000个素数,即1299709。输入的末尾由一条包含单个零的线表示。

输出:

        输出应该由行组成,每行包含一个非负整数。如果输入中包含相应的正整数,则为素数间隙的长度,否则为0。输出中不应出现其他字符。

样例输入:

10
11
27
2
492170
0

样例输出:

4
0
6
0
114

3.题意

输入一个数,若为素数则输出0,非素数时,用向后到达的第一素数减去向前的第一个素数。

4.代码

#encoding=utf-8
#素数判定
def isprime(num):
    if num<2:
        return False
    else:
        for i in range(2,int(num**1/2)+1):
            if num%i==0:
                return False
        return True
    
#计算大于这个合数的第一个素数和小于这个合数的第一个素数的差
def prime_gap(num):
    for i in range(num,1,-1):
        if isprime(i):
            minprime=i
            break
    while True:
        num+=1
        if isprime(num):
            maxprime=num
            break
    return maxprime-minprime
#保存输出结果的list
output_list=[]

#主程序
while True:
    num=int(input())
    if num==0:
        break
    else:
        if isprime(num):
            output_list.append(0)
        else:
            output_list.append(prime_gap(num))

#输出
for i in output_list:
    print(i)

5.知识点

这道题和OJ Digit Primes强调的知识点一样,唯一多的一点就是:

range的倒序处理:

for i in range(10,1,-1):
    print(i)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值