3n 1數列問題

2021-08-24 18:11:30 字數 1823 閱讀 8257

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

10 5

sample output

2 4 8 5 16

#include 

#include

struct node

;struct node *creat (int n,int k)

else

q=head;

while(q->next)

p->data=n;

p->next=null;

q->next=p;

q=p;

}else

k--;

}return head;

}void print(struct node *head)

else

p=p->next;

}}int main()

return

0;}

先解釋輸出函式:為啥外層迴圈是p!=null;裡層是p->next !=null;外層是讓指標一直指向下乙個,直到沒有。內層最後一項的next 是null,也就是不能到達最後一項。

建立函式:先建乙個頭;如果是奇數,也就是順序建表,讓q指向尾節點,方法是先讓他指向頭結點或者收個節點,然後一直指向尾部。然後讓p插在最後。每次都要找尾節點。

#include 

#include

struct node

;struct node *creat (int n,int k)

else

}k--;

}return head;

}void print(struct node *head)

else

p=p->next;

}}int main()

return

0;}

3n 1數列問題

time limit 1000ms memory limit 65536k 有一天小標遇到了經典的3n 1數鏈問題,他想知道3n 1數鏈的前k個數是多少。下面小標來給你介紹一下3n 1數鏈是什麼,給定乙個數n,如果n為偶數,那麼下乙個數n1 n 2 否則n1 3 n 1 如果n1為偶數,那麼下乙個數...

3n 1數列問題

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 ...

3n 1數列問題

time limit 1000ms memory limit 65536kb problem description 有一天小標遇到了經典的3n 1數鏈問題,他想知道3n 1數鏈的前k個數是多少。下面小標來給你介紹一下3n 1數鏈是什麼,給定乙個數n,如果n為偶數,那麼下乙個數n1 n 2 否則n1...