Prime Ring Problem

小灰灰 2022-05-16 09:06 309阅读 0赞

Prime Ring Problem

A ring is compose of n circles as shown in diagram. Put natural number 1, 2, …, n into each circle separately, and the sum of numbers in two adjacent circles should be a prime.

Note: the number of first circle should always be 1.

这里写图片描述

Input
n (0 < n < 20).

Output
The output format is shown as sample below. Each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above requirements. Print solutions in lexicographical order.

You are to write a program that completes above process.

Print a blank line after each case.

Sample Input
6
8

Sample Output
Case 1:
1 4 3 2 5 6
1 6 5 2 3 4

Case 2:
1 2 3 8 5 6 7 4
1 2 5 8 3 4 7 6
1 4 7 6 5 8 3 2
1 6 7 4 3 8 5 2

  1. #include <cstdio>
  2. #include <iostream>
  3. #include <cmath>
  4. using namespace std;
  5. //判断素数
  6. int isprime(int n)
  7. {
  8. int i;
  9. if(n==1) return false;
  10. for(i=2;i<=sqrt(n);i++)
  11. if(n%i==0)
  12. return false;
  13. return true;
  14. }
  15. //判断当前序列是否满足条件
  16. int isok(int a[],int last,int curvalue)//curvalue是当前值,a[last]是前一个值
  17. {
  18. if(last<0) return true;//第一个元素没有前驱元素 返回真
  19. if(!((curvalue+a[last])&1))//相邻元素和为偶数,偶数肯定不是素数!
  20. return false;
  21. if(!(isprime(curvalue+a[last])))//相邻元素和不为素数
  22. return false;
  23. for(int i=0;i<=last;i++)
  24. if(a[i]==curvalue)//去重curvalue没有出现过
  25. return false;
  26. return true;
  27. }
  28. //输出
  29. void print(int a[],int n)
  30. {
  31. for(int i=0;i<n-1;i++)
  32. printf("%d ",a[i]);
  33. printf("%d\n",a[n-1]);
  34. }
  35. void primecircle(int a[],int n,int t)
  36. {
  37. if(n&1)//输入N为奇数,肯定不满足,因为肯定会有两个奇数排在一起~
  38. return ;
  39. if(t==n)
  40. {
  41. if(isprime(a[0]+a[n-1]))
  42. print(a,n);
  43. }
  44. else{
  45. for(int i=2;i<=n;i++)
  46. {
  47. a[t]=i;
  48. if(isok(a,t-1,i))//如果当前元素满足条件
  49. primecircle(a,n,t+1);
  50. }
  51. }
  52. }
  53. int main()
  54. {
  55. int a[30],n,k=1,i,j;
  56. while(scanf("%d",&n)!=EOF){
  57. printf("Case %d:\n",k++);
  58. a[0]=1;
  59. isprime(a[0]);
  60. for(i=1,j=2;i<n;i++,j++){
  61. a[i]=j;
  62. isprime(a[i]);
  63. }
  64. primecircle(a,n,1);
  65. printf("\n");
  66. }
  67. return 0;
  68. }

有一篇关于素数环博客写的特别好,有兴趣的可以参考#本人的收藏#~~嘻嘻 希望对你有帮助~

发表评论

表情:
评论列表 (有 0 条评论,309人围观)

还没有评论,来说两句吧...

相关阅读