classSolution { private: inlineboolisPrime(int n){ if (n == 1) { returnfalse; } for (int i = 2; i * i <= n; i++) { if (n % i == 0) { returnfalse; } } returntrue; } public: intmaximumPrimeDifference(vector<int>& nums){ int m = 10000000, M = -1; for (int i = 0; i < nums.size(); i++) { if (isPrime(nums[i])) { m = min(m, i); M = max(M, i); } } return M - m; } };
funcmax(a int, b int)int { if a > b { return a } return b }
funcmin(a int, b int)int { if a < b { return a } return b }
funcisPrime(n int)bool { if n == 1 { returnfalse } for i := 2; i * i <= n; i++ { if n % i == 0 { returnfalse } } returntrue }
funcmaximumPrimeDifference(nums []int)int { M, m := -1, 10000000 for i := 0; i < len(nums); i++ { if isPrime(nums[i]) { M = max(M, i) m = min(m, i) } } return M - m }
classSolution { privatebooleanisPrime(int n) { if (n == 1) { returnfalse; } for (inti=2; i * i <= n; i++) { if (n % i == 0) { returnfalse; } } returntrue; }
publicintmaximumPrimeDifference(int[] nums) { intm=10000000, M = -1; for (inti=0; i < nums.length; i++) { if (isPrime(nums[i])) { m = Math.min(m, i); M = Math.max(M, i); } } return M - m; } }
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
from typing importList from math import sqrt
classSolution: defisPrime(self, n: int) -> bool: if n == 1: returnFalse for i inrange(2, int(sqrt(n)) + 1): if n % i == 0: returnFalse returnTrue
defmaximumPrimeDifference(self, nums: List[int]) -> int: m, M = 10000000, -1 for i inrange(len(nums)): ifself.isPrime(nums[i]): m, M = min(m, i), max(M, i) return M - m