Kody źródłowe/Problem Collatza
Wygląd
C++
[edytuj]#include <iostream>
#include <list>
using namespace std;
int collatz(unsigned int c) {
return (c % 2 == 0) ? c/2 : (3 * c) + 1;
}
int main() {
unsigned long int c;
list<unsigned int> data;
cout << "Wpisz liczbe c:\n";
cin >> c;
while (c != 1) {
c = collatz(c);
data.push_back(c);
}
for (unsigned int i : data) {
cout << i << '\n';
}
return 0;
}
Lisp
[edytuj](defun collatz (c)
(if (= (% c 2) 0)
(/ c 2)
(+ (* 3 c) 1)))
collatz
(defun collatz-to-1 (l)
(do ((arg l)
(wynik nil))
((= arg 1) (cons l (reverse wynik)))
(setq arg (collatz arg))
(setq wynik (cons arg wynik))))
Python
[edytuj]def collatz(c):
while c > 1:
if c % 2:
c = 3 * c + 1
else:
c /= 2
yield c
for i in collatz(6):
print(i)