数论对编写程序重要吗?

数论对编写程序重要吗?,第1张

我不是老师,我想说的是你编算法的话还是有用的,比如质数判定法,最小公倍数,判定超越数等,这些程序的编写离不开数论中已得的结果,有些证明非常深刻,但对于我们只需要利用他们的公式将公式程序话就行了。

你的output好像有问题,1 10 5好像有解

#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下通过 */


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/11174991.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-14
下一篇 2023-05-14

发表评论

登录后才能评论

评论列表(0条)

保存