3n+1数列问题

Bertha 。 2022-05-13 10:16 231阅读 0赞

3n+1数列问题

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic

Problem Description

有一天小标遇到了经典的3n+1数链问题,他想知道3n+1数链的前k个数是多少。
下面小标来给你介绍一下3n+1数链是什么,
给定一个数n,如果n为偶数,那么下一个数n1 = n / 2;否则n1 = 3 * n + 1;
如果n1为偶数,那么下一个数n2 = n1 / 2;否则n2 = 3 * n1 + 1;
如果n2为偶数,那么下一个数n3 = n2 / 2;否则n3 = 3 * n2 + 1;
…..
小标最近刚刚学习了链表,他想把这两个知识结合一下,所以,他想按照下面的规定去做。
①起始n为10,k为5,链表为空
②判断n为偶数,他会往链表头部加一个5(即n/2),此时链表中序列为5,n变为5 -> NULL
③接下来n==5,判断n为奇数,他会往链表尾部加一个16(即3*n+1),此时链表中序列为5 -> 16 -> NULL
④接下来n==16,判断n为偶数,他会往链表头部加一个8(即n/2),此时链表中序列为8 -> 5 -> 16 -> NULL
⑤接下来n==8,判断n为偶数,他会往链表头部加一个4(即n/2),此时链表中序列为4 - > 8 - > 5 -> 16 -> NULL
⑥接下来n==4,判断n为偶数,他会往链表头部加一个2(即n/2),此时链表中序列为2 - > 4 - > 8 - > 5 -> 16 -> NULL
到此时,小标得到了前k个数,那么输出这个序列。
Ps: 为了变得更容易理解,简单来说就是n为偶数,加在链表头部,n为奇数,加在链表尾部

Input

多组输入。
对于每组数据,每行两个整数1 <= n , k <= 1000,含义如上

Output

输出链表序列

Sample Input

  1. 10 5

Sample Output

  1. 2 4 8 5 16

Hint

Source

2015级《程序设计基础II》计科软件通信期末上机考试2

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. struct node
  4. {
  5. int data;
  6. struct node *next;
  7. };
  8. int main()
  9. {
  10. struct node *head, *tail, *p, *q;
  11. int n, num, k;
  12. while(scanf("%d%d", &n, &k) != EOF)
  13. {
  14. head = (struct node *)malloc(sizeof(struct node));
  15. tail = (struct node *)malloc(sizeof(struct node));
  16. head->next = NULL;
  17. num = 1;
  18. if(n % 2 == 0 && num == 1)
  19. {
  20. p = (struct node *)malloc(sizeof(struct node));
  21. p->data = n / 2;
  22. head->next = p;
  23. p->next = NULL;
  24. num = 2;
  25. n = n / 2;
  26. }
  27. if(n % 2 == 1 && num == 1)
  28. {
  29. p = (struct node *)malloc(sizeof(struct node));
  30. p->data = 3 * n + 1;
  31. head->next = p;
  32. p->next = NULL;
  33. num = 2;
  34. n = 3 * n + 1;
  35. }
  36. k = k - 1;
  37. tail = p;
  38. while(k--)
  39. {
  40. if(n % 2 == 0)
  41. {
  42. q = (struct node *)malloc(sizeof(struct node));
  43. q->data = n / 2;
  44. q->next = head->next;
  45. head->next = q;
  46. n = n / 2;
  47. }
  48. else
  49. {
  50. q = (struct node *)malloc(sizeof(struct node));
  51. q->data = n * 3 + 1;
  52. q->next = NULL;
  53. tail->next = q;
  54. tail = q;
  55. n = n * 3 + 1;
  56. }
  57. }
  58. for(p = head->next; p ->next != NULL; p = p->next)
  59. {
  60. printf("%d ", p->data);
  61. }
  62. printf("%d\n", p->data);
  63. }
  64. return 0;
  65. }

发表评论

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

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

相关阅读

    相关 1+2+3+...+n

    题目:计算1+2+3+…+n,要求:不使用if, while, for, switch, case等关键字及三目运算符。 看到题目要求不能使用这么多关键字,那么可以考虑用

    相关 3n+1数列问题

    Problem Description 有一天小标遇到了经典的3n+1数链问题,他想知道3n+1数链的前k个数是多少。 下面小标来给你介绍一下3n+1数链是什么,

    相关 (3n+1)猜想

    卡拉兹(Callatz)猜想: 对任何一个正整数 n,如果它是偶数,那么把它砍掉一半;如果它是奇数,那么把 (3n+1) 砍掉一半。这样一直反复砍下去,最后一定在某一步得到