我试图找到2个素数,这些素数总和到用户指定的某个整数N.但是我得到了MLE的这个错误
def is_prime(n):
if n == 2:
return True
if n%2 == 0 or n <= 1:
return False
sqr = int(n**0.5) + 1
for divisor in range(3, sqr, 2):
if n%divisor == 0:
return False
return True
class Solution:
# @param A : integer
# @return a list of integers
def primesum(self, A):
#Creating the list of prime numbers
h_prime ={}
# Initializing the hash table
# looking for the prime numbers
for i in range (2, long (A)):
if ( is_prime(i)):
h_prime [i] = A-i;
# Checking if the compliment is also a prime
#We go through it element by element
for key in h_prime:
if key in h_prime and A-key in h_prime:
my_list = [ key, A-key]
return my_list
答案 0 :(得分:0)
由于问题提示者似乎不想澄清,我会在Go中回答,因为我最近在练习它!
package main
import (
"fmt"
"math"
)
func isPrime(n int) bool {
if n == 2 {
return true
} else if n%2 == 0 || n <= 1 {
return false
} else {
sqrt := int(math.Floor(math.Sqrt(float64(n)))) + 1
for divisor := 3; divisor < sqrt; divisor += 2 {
if n%divisor == 0 {
return false
}
}
return true
}
}
func PrimesSum(n int) (int, int, error) {
primes := make(map[int]struct{})
for i := 2; i <= n; i++ {
if isPrime(i) {
primes[i] = struct{}{}
}
}
for primeOne, _ := range primes {
primeTwo := n - primeOne
_, ok := primes[primeTwo]
if ok {
return primeOne, primeTwo, nil
}
}
return 0, 0, fmt.Errorf("No prime sum for %v", n)
}
func main() {
var i int
fmt.Println("Enter a number to check: ")
fmt.Print(">> ")
_, err := fmt.Scan(&i)
if err == nil {
primeOne, primeTwo, err := PrimesSum(i)
if err == nil {
fmt.Printf("%v, %v\n", primeOne, primeTwo)
} else {
fmt.Print(err)
}
} else {
fmt.Printf("Invalid input, %v\n", err)
}
}