George Burrows
George Burrows

Reputation: 3501

Collatz Conjecture and printing statements

I am trying to create a simple program to apply the statement of the Collatz Conjecture to an integer that the user can enter, I have:

def collatz(n):
    print n,
    if n % 2 ==0:
        n = n / 2
    elif n == 0:
        Print "Collatz Conjecture true for" , 'n'
    else:
        n = n *3 + 1

input("\n\nInsert a positive integer:")
def collatz(n)

However it is saying there is a syntax error in the line:

Print "Collatz Conjecture true for" , 'n'

I can't see what mistake ther is in this line.

Also as I haven't been able to test it yet, does this look as though it will work ok?

Upvotes: 0

Views: 2080

Answers (4)

Daniel
Daniel

Reputation: 429

 def collatz_steps(n):
    steps=0
    if n==1:
        return 0 
    else:
        while n!=1:
            if n%2==0:
                n=n/2
                steps+=1
            else:
                n = 3*n+1
                steps+=1
        return steps

Upvotes: 0

Daniel Fischer
Daniel Fischer

Reputation: 183968

More problems:

  1. The stopping condition should be n == 1, not n == 0.
  2. You have to recur or iterate, as is you're only making one step.
  3. Check the input, make sure it really is a positive number.

Upvotes: 2

Andrew Jaffe
Andrew Jaffe

Reputation: 27097

Well, your syntax error is that python is case-sensitive, so you need print rather than Print.

But you've got more problems:

  • 'n' prints the string n. I think what you want is n to print the value of the variable (or if not, then you can just make a single string "... true for n").

  • Finally (I think), in order to run the function collatz, you don't need the def; that's just for the definition.

Upvotes: 3

Godeke
Godeke

Reputation: 16281

Python is case sensitive. Use "print" not "Print".

Upvotes: 3

Related Questions