collatz

Do you know how to write this Scheme function?

Could you write a function that takes one argument (a positive integer) and divides it by two if it's even, or multiplies it by three and adds one if it's odd and then returns the resulting number. And then a separate function that takes one argument (a positive integer) and repeatedly passes it to the previous function until it rea...

Project Euler (P14): recursion problems

Hi I'm doing the Collatz sequence problem in project Euler (problem 14). My code works with numbers below 100000 but with numbers bigger I get stack over-flow error. Is there a way I can re-factor the code to use tail recursion, or prevent the stack overflow. The code is below: import java.util.*; public class v4 { // use a HashM...

Uva's 3n+1 problem

I'm solving Uva's 3n+1 problem and I don't get why the judge is rejecting my answer. The time limit hasn't been exceeded and the all test cases I've tried have run correctly so far. import java.io.*; public class NewClass{ /** * @param args the command line arguments */ public static void main(String[] args) th...

why is my 3n+1 problem solution wrong?

I have recently started reading "Programming Challenges" book by S. Skiena and believe or not I am kind of stuck in the very first problem. Here's a link to the problem: 3n+1 problem Here's my code: #include <iostream> #include <vector> #include <algorithm> using namespace std; unsigned long calc(unsigned long n); int main() { ...

Code Golf: Collatz Conjecture

Inspired by http://xkcd.com/710/ here is a code golf for it. The Challenge Given a positive integer greater than 0, print out the hailstone sequence for that number. The Hailstone Sequence See Wikipedia for more detail.. If the number is even, divide it by two. If the number is odd, triple it and add one. Repeat this with the n...

Why doesn't this loop terminate?

Here's the sample code: public static void col (int n) { if (n % 2 == 0) n = n/2 ; if (n % 2 != 0) n = ((n*3)+1) ; System.out.println (n) ; if (n != 1) col (n) ; } this works just fine until it gets down to 2. then it outputs 2 4 2 4 2 4 2 4 2 4 infinitely. it seems to me that if 2 is entered...

Lazy Sequences that "Look Ahead" for Project Euler Problem 14

I'm trying to solve Project Euler Problem 14 in a lazy way. Unfortunately, I may be trying to do the impossible: create a lazy sequence that is both lazy, yet also somehow 'looks ahead' for values it hasn't computed yet. The non-lazy version I wrote to test correctness was: (defn chain-length [num] (loop [len 1 n num] (con...

[Haskell] Error "No instance for (Num [t])" in Collatz function

I am new to Haskell, and programming in general. I am trying to define a function which generates the sequence of Collatz numbers from n. I have: collatz n = (collatz' n) : 1 where collatz' n = (takeWhile (>1) (collatz'' n)) where collatz'' n = n : collatz'' (collatz''' n) where collatz''' 1 = 1 ...