#include <iostream>
#include <string>
int is_prime(int n) {
if(n % 2 == 0) return 0
for(int i = 3i <n / 2i = i + 2) {
if(n % i == 0) return 0
}
return 1
}
int has_duplicate(int seq[], int index, int num) {
for (int j = 0j <indexj++) {
if (seq[j] == num)
return 1
}
return 0
}
int anti_prime_seq(int n, int seq[], int length, int d, int index) {
for (int i = ni <n + lengthi++) {
seq[index] = i
// check duplicate from 0 up to index, skip if so
if (has_duplicate(seq, index, i))
continue
// check if sum of numbers from [index - d + 1] to [index] is a composite, skip if prime
if (index >d - 2) {
int sum = 0
for (int j = indexj >index - dj--)
sum += seq[j]
if (is_prime(sum)) {
if (index == length - 1)
return 0
continue
}
if (index == length - 1)
return 1
}
// next index
if (anti_prime_seq(n, seq, length, d, index + 1)) {
return 1
} else
continue
}
return 0
}
typedef struct struct_aps {
int n, m, d
struct struct_aps* next
} aps
int main(int argc, char* argv[]) {
int n = 1, m = 10, d = 5, *seq
aps *input_head = new aps, *input_tail = input_head
// initialize the head of list
input_tail->n = 0
input_tail->m = 0
input_tail->d = 0
input_tail->next = 0
std::cout <<"Input: n m d\n"
while (1) {
std::cin >>n >>m >>d
if (n == 0&&m == 0&&d == 0)
break
// create a node
input_tail->next = new aps
input_tail = input_tail->next
input_tail->n = n
input_tail->m = m
input_tail->d = d
input_tail->next = 0
}
std::cout <<"\nOutput:\n"
while (1) {
if (input_head->next != 0) {
input_tail = input_head->next
input_head->next = input_tail->next
// release node heap
n = input_tail->n
m = input_tail->m
d = input_tail->d
delete input_tail
input_tail = 0
seq = new int[m - n + 1]
if (anti_prime_seq(n, seq, m - n + 1, d, 0)) {
for (int i = 0i <m - n + 1i++) {
std::cout <<seq[i] <<" "
}
} else
std::cout <<"No anti-prime sequence exists."
std::cout <<std::endl
// release seq
delete [] seq
} else break
}
// release head node heap
delete input_head
input_head = 0
return 0
}
/* MinGW下通过 */
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)