Ask Your Question

How to do an "if" block in Sage?

asked 2014-07-09 16:36:24 -0500

ClemFanJC07 gravatar image

updated 2014-07-09 16:58:01 -0500

calc314 gravatar image

I am trying to do an if block in sage. For example, I have code:

for n in range(7):
    if gcd(n,3)==3:

This "should" only add one when n is divisible by 3, but seems to do this all the time. Any ideas?

edit retag flag offensive close merge delete


Specifically, I am trying to sum up al multinomial coefficients that have two equal parts. I am using the code: for n in range(21): t=0; for i in range(n+1): t = t + Combinations(n,i).cardinality()*Combinations(n-i,i).cardinality(); t=3*t; if gcd(n,3)==3: t = t-2*Combinations(n, n/3).cardinality()*Combinations(2*n/3, n/3).cardinality(); print t However, for n=3 the answer should be 18 not 15. Ideas?

ClemFanJC07 gravatar imageClemFanJC07 ( 2014-07-09 16:43:02 -0500 )edit

Can you put the code from your comment in your original question so we can see the formatting better?

calc314 gravatar imagecalc314 ( 2014-07-09 17:01:31 -0500 )edit

For your first bit of code, if you print n before and after your "if" block, you will see that the value of n is only modified when n is divisible by 3.

calc314 gravatar imagecalc314 ( 2014-07-09 17:04:36 -0500 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2014-07-09 17:17:08 -0500

Rolandb gravatar image

updated 2014-07-26 01:04:34 -0500

Maybe you get confused by the fact that gcd(0,3) equals 3. If I print each step, it works as expected.

for n in range(9):
    print "n=",n
    if gcd(n,3)==3:
        print "?"
    print "*",n

n= 0
* 1
n= 1
* 1
n= 2
* 2
n= 3
* 2
n= 4
* 4
n= 5
* 5
n= 6
* 3
n= 7
* 7
n= 8
* 8
edit flag offensive delete link more



If you indent by 4 spaces the code and outpout that you pasted in your answer, it will be displayed nicely in a code block. When editing your answer, you can also select the relevant lines and click the "code" button which has little digits "101 010", next to the "bold", "italics" etc buttons, and this will put your code in an appropriate block so that it will be displayed nicely.

slelievre gravatar imageslelievre ( 2014-07-09 20:51:06 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2014-07-09 16:36:24 -0500

Seen: 102 times

Last updated: Jul 26 '14