[英]The next prime number
在兩個數字的給定輸入中,檢查第二個數字是否恰好是第一個數字的下一個素數。 如果是,則返回“YES”,否則返回“NO”。
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int nextPrime(int x){
int y =x;
for(int i=2; i <=sqrt(y); i++){
if(y%i == 0){
y = y+2;
nextPrime(y);
return (y);
}
}
return y;
}
int main()
{
int n,m, x(0);
cin >> n >> m;
x = n+2;
if(n = 2 && m == 3){
cout << "YES\n";
exit(0);
}
nextPrime(x) == m ? cout << "YES\n" : cout << "NO\n";
return 0;
}
我的代碼在哪里運行錯誤? 僅當下一個數字是 +2 或 +4 時才返回 true。 也許它與return語句有關。
與return語句有關
我會這么說
y = y+2;
nextPrime(y);
return (y);
可以替換為
return nextPrime(y + 2);
您的版本調用 nextPrime 但沒有對返回值做任何事情,而是只返回y
。
用另一個循環編寫 nextPrime 函數會更常見,而不是編寫遞歸函數。
我可以告訴你兩件事你做錯了:
輸入2 4
,您將永遠檢查 4, 6, 8, 10, 12, 14, 16, 18, ... 的素數。
另一件事是
y = y+2;
nextPrime(y);
return (y);
應該只是
return nextPrime(y + 2);
除此之外,您的循環效率非常低:
for(int i=2; i <=sqrt(y); i++){
將偶數作為特殊情況處理,然后使用
for(int i=3; i * i <= y; i += 2){
使用不同的素數測試也會更快。 例如 Miller-Rabin 素性檢驗:
#include <iostream>
#include <cstdint>
#include <array>
#include <ranges>
#include <cassert>
#include <bitset>
#include <bit>
// square and multiply algorithm for a^d mod n
uint32_t pow_n(uint32_t a, uint32_t d, uint32_t n) {
if (d == 0) __builtin_unreachable();
unsigned shift = std::countl_zero(d) + 1;
uint32_t t = a;
int32_t m = d << shift;
for (unsigned i = 32 - shift; i > 0; --i) {
t = ((uint64_t)t * t) % n;
if (m < 0) t = ((uint64_t)t * a) % n;
m <<= 1;
}
return t;
}
bool test(uint32_t n, unsigned s, uint32_t d, uint32_t a) {
uint32_t x = pow_n(a, d, n);
//std::cout << " x = " << x << std::endl;
if (x == 1 || x == n - 1) return true;
for (unsigned i = 1; i < s; ++i) {
x = ((uint64_t)x * x) % n;
if (x == n - 1) return true;
}
return false;
}
bool is_prime(uint32_t n) {
static const std::array witnesses{2u, 3u, 5u, 7u, 11u};
static const std::array bounds{
2'047u, 1'373'653u, 25'326'001u, 3'215'031'751u, UINT_MAX
};
static_assert(witnesses.size() == bounds.size());
if (n == 2) return true; // 2 is prime
if (n % 2 == 0) return false; // other even numbers are not
if (n <= witnesses.back()) { // I know the first few primes
return (std::ranges::find(witnesses, n) != std::end(witnesses));
}
// write n = 2^s * d + 1 with d odd
unsigned s = 0;
uint32_t d = n - 1;
while (d % 2 == 0) {
++s;
d /= 2;
}
// test widtnesses until the bounds say it's a sure thing
auto it = bounds.cbegin();
for (auto a : witnesses) {
//std::cout << a << " ";
if (!test(n, s, d, a)) return false;
if (n < *it++) return true;
}
return true;
}
是的,這是一個非常多的代碼,但它運行的次數很少。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.