编写一个程序,提示用户输入大于2的偶数整数。
给定Goldbach的猜想,即每一个大于2的偶数都可以表示为两个素数之和,打印出两个素数,相加后提供所请求的偶数。编辑:程序只需要打印一对素数,而不是全部。例如:
4:2+2
6: 3+3
8: 3+5
10: 5+5或3+7
发布于 2014-01-27 22:37:30
第一个版本的符号长度为34个,仅限于原始单字节APL字符集中的字符,例如Dyalog APL中仍然支持的字符:
↑c/⍨n=+/¨c←,∘.,⍨v/⍨~v∊v∘.×v←1↓⍳n←⎕解释:
n←⎕ ⍝ ask for a number, store as n
v←1↓⍳n ⍝ generate all integers from 2 to n
v∘.×v ⍝ compute the product table of any two such integers
v/⍨~v∊ ⍝ select those that don't appear in the product table
c←,∘.,⍨ ⍝ generate all possible pairs of these primes
n=+/¨c ⍝ check which pairs have a sum equal to n
↑c/⍨ ⍝ take the first that does第二个版本只有22个符号长,因为它利用π函数来检查素数,但只有在使用Unicode的NARS2000中才可用,所以UCS-2中的字节计数是44:
2⍴(⌿⍨{∧/0π⍵})(⍪,⌽)⍳⎕-1解释:
⎕ ⍝ ask for a number N
⍳ -1 ⍝ generate all naturals from 1 to N-1
(⍪,⌽) ⍝ arrange it into a table of all pairs of naturals with sum N
{∧/0π⍵} ⍝ check which pairs are made of all primes
2⍴(⌿⍨ ) ⍝ return the first pair that does(⎕:是提示符要求一个号码)
2⍴(⌿⍨{∧/0π⍵})(⍪,⌽)⍳⎕-1
⎕:
4
2 2
2⍴(⌿⍨{∧/0π⍵})(⍪,⌽)⍳⎕-1
⎕:
6
3 3
2⍴(⌿⍨{∧/0π⍵})(⍪,⌽)⍳⎕-1
⎕:
8
3 5
2⍴(⌿⍨{∧/0π⍵})(⍪,⌽)⍳⎕-1
⎕:
124
11 113发布于 2014-01-27 12:13:25
require'prime'
n=gets.to_i
Prime.find{|i|p [i,n-i]if(n-i).prime?}发布于 2014-02-02 19:54:27
基本上是对第二部分的改进(我在2.7上做了这个测试,但我认为它也适用于3.x)。
p=lambda x:all(x%i!=0 for i in range(2,x))
n=input()
for i in range(2,n-1):
if p(i)&p(n-i): print i,n-ihttps://codegolf.stackexchange.com/questions/19463
复制相似问题