uva 524 - Prime Ring Problem
来源:互联网 发布:java统计报表怎么做 编辑:程序博客网 时间:2024/06/01 23:51
A ring is composed of n (even number) circles as shown in diagram. Put natural numbers 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 <= 16)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.
You are to write a program that completes above process.
Sample input:
68
Sample output:
Case 1:1 4 3 2 5 61 6 5 2 3 4Case 2:1 2 3 8 5 6 7 41 2 5 8 3 4 7 61 4 7 6 5 8 3 21 6 7 4 3 8 5 2
#include <math.h>#include <stdio.h>int N;int result[50];int visit[50];int is_prime(int n){int max = sqrt(n);int i = 2;while(i <= max){if(n % i == 0){return 0;}i++;}return 1;}void print_result(void){int i = 1;while(i <= N){printf("%d ", result[i]);i++;}printf("\n");}void search(int current_count){if(current_count == N && is_prime(1 + result[current_count])){print_result();visit[result[current_count]] = 0;return;}int i;for(i = 2; i <= N; i++){if(visit[i] == 0 && is_prime(i + result[current_count]) ){visit[i] = 1;result[current_count + 1] = i;search(current_count + 1);}}visit[result[current_count]] = 0;}int main(int argc, char **argv){int i = 1;while(scanf("%d", &N) != EOF){result[1] = 1;visit[1] = 1;printf("Case %d:\n", i);i++;search(1);}return 0;}
这个代码可以从下面两点优化:
1. 预先把数字是否为质数保存到数组里面,而不是一个个的去计算。
2. 考虑到数字的奇偶行,下面一行可:
for(i = 2; i <= N; i++)可以改为:
for(i = (current_count+1) %2 + 2; i <= N; i+=2)
References:
1. http://www.programering.com/a/MTMwIDNwATU.html
2. http://www.tuicool.com/articles/Ezuum2a
0 0
- UVA 524 - Prime Ring Problem
- uva 524 - Prime Ring Problem
- uva 524 Prime Ring Problem
- UVa:524 Prime Ring Problem
- uva 524 - Prime Ring Problem
- UVa 524 - Prime Ring Problem
- UVA - 524 Prime Ring Problem
- UVa-524 - Prime Ring Problem
- UVA - 524 Prime Ring Problem
- UVa - 524 - Prime Ring Problem
- UVA - 524 Prime Ring Problem
- uva 524Prime Ring Problem
- uva 524 - Prime Ring Problem
- Prime Ring Problem(UVA 524)
- UVA - 524 Prime Ring Problem
- UVA - 524 Prime Ring Problem
- UVa 524 Prime Ring Problem
- UVA 524 Prime Ring Problem
- 推送通知的跳转
- 百度首页(HTML5)
- mono中的内存泄漏和WeakReference(弱引用)的使用
- Andrid5.0新特性——SVG(可缩放矢量图)
- ubuntu 14.04 利用ap-hotspot建立wifi热点失效
- uva 524 - Prime Ring Problem
- codeforces 675-E Trains and Statistic 线段树+dp
- Centos中搭建python3开发环境
- 2. SpringMVC_HelloWorld
- 9.3顺序容器操作
- Codeforces Beta Round #2
- Android gridview 使用的一些小问题
- HDU 1864 最大报销额 (dp 01背包)
- 采访 Gaijin Entertainment游戏Crossout,先睹为快吧