中級 0件解決済み 正答率0%

Circular Primes

Count the primes up to a limit whose every digit rotation is also prime.

このチャレンジで学べること

  • Rotate the digits of a number
  • Check a condition on every rotation
  • Count numbers that pass

問題

翻訳を表示

Rotating a number moves its first digit to the end: 197 becomes 971, then 719. A prime is circular when every rotation is prime too, so 197 is circular. Count the circular primes from 2 to limit. A rotation may be larger than the limit; it still has to be prime.

Implement circular_primes(limit).

Input

limit: The largest number to check.

Output

Return how many primes p ≤ limit are circular.

制約

1 ≤ limit ≤ 100,000

例

例 1
入力:
limit = 20

期待される出力:
expected = 7
入力:
long long limit = 20;

期待される出力:
long long expected = 7;
入力:
long limit = 20;

期待される出力:
long expected = 7;

解説

2, 3, 5, 7, 11, 13 (31 is prime) and 17 (71 is prime) are circular, but 19 is not (91 = 7 × 13): 7.

例 2
入力:
limit = 1

期待される出力:
expected = 0
入力:
long long limit = 1;

期待される出力:
long long expected = 0;
入力:
long limit = 1;

期待される出力:
long expected = 0;

解説

There are no primes up to 1, so the answer is 0.

解き方のヒント

まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。

ヒント 1

Rotating once moves the first digit to the end; a d-digit number has d rotations.

ヒント 2

Turning the number into a string makes rotation easy.

ヒント 3

Rotations can be bigger than the limit, so test them for primality directly.

目安の計算量

O(limit × d × √(10^d)) time with trial division, O(d) extra space

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

まだ合格した解答はありません。解いて 1 位になりましょう。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。