Trung bình 0 đã giải Tỷ lệ chấp nhận 0%

Circular Primes

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

Bạn sẽ học được gì

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

Đề bài

Xem bản dịch

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.

Ràng buộc

1 ≤ limit ≤ 100,000

Ví dụ

Ví dụ 1
Đầu vào:
limit = 20

Kết quả mong đợi:
expected = 7
Đầu vào:
long long limit = 20;

Kết quả mong đợi:
long long expected = 7;
Đầu vào:
long limit = 20;

Kết quả mong đợi:
long expected = 7;

Giải thích

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

Ví dụ 2
Đầu vào:
limit = 1

Kết quả mong đợi:
expected = 0
Đầu vào:
long long limit = 1;

Kết quả mong đợi:
long long expected = 0;
Đầu vào:
long limit = 1;

Kết quả mong đợi:
long expected = 0;

Giải thích

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

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

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

Gợi ý 2

Turning the number into a string makes rotation easy.

Gợi ý 3

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

Độ phức tạp mong đợi

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

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

Chưa có lời giải nào đạt. Giải bài này để giành hạng nhất.

Học hỏi từ người khác

Giải pháp cộng đồng

Chưa có giải pháp nào được chia sẻ. Hãy giải thử thách này để đăng giải pháp đầu tiên.