0

I'm very beginner at python. Given code gives error with output. Want to correct it.

The mathematics behind the code is :

Let denote $S_m(n)=1^m+2^m+...+n^m$ and denote $D_x(y)$ is sum of digits of $y$ in base $x$.

Example $S_2(3)=14$ and $14=(1,1,1,0)_2$ then $D_2(14)=3$

Theorem if $x-1\mid y$ then $x-1\mid D_x(y)$

In code, for $n$, output shows "divisible" if $n-1\mid S_m(n-1)$ and shows "oooooooooook" if $n-1\mid D_n(S_m(n-1))$

Problem codes output must show "oooooooooook" if "divisible" had shown but greater value $m$ with greater $n$ does not shows expected result. How to correct it?

n= 2
m = 15
while n < 100:
    print("\n n=",n)

    num=n
    sum_num = 0
    for i in range(1, num): 
        sum_num += i**(m)
    n2 = (sum_num)


    if(n2%(num-1)== 0):
        print("diviasible")
    #else:
        #print("not divisible")

    rem_array = []
    while n2 != 0:
        mod = n2%n
        if mod != 0:
          rem = mod
          n2 = n2 - rem
          rem_array.append(round(rem))
          n2 = n2/n
        else:
            n2 = n2/n
            rem_array.append(0)

    #print(rem_array[::-1],sum(rem_array))

    if(sum(rem_array)%(n-1)==0):
        print("oooooooooook")
    #else:
        #print("not ok")



    n += 1

Thank you

Pruthviraj
  • 2,707

2 Answers2

1

Not a full solution, but your sum computation is very un-pythonic. You should use list comprehension instead:

num=15
m=5
s = [i*m for i in range(1,num)]
total_sum = sum(s)

Or, use lambda function + map:

f = lambda x:x*s
s= map(f, range(1,10))
total_sum=sum(s)
Alex
  • 19,262
1

Don't see all the points that are not ok, but using // integer division instead of / float division somewhat helps (tested, that worked).
Let me re-write the entire program:

s=lambda m,n:sum(i**m for i in range(1,n+1))
def digits(x,y):
    res=[]
    while y:
        res.append(y%x)
        y//=x
    return res
m=15
#theorem:
for n in range(2,101):
    s_m=s(m,n-1)
    assert s_m%(n-1) !=0 or sum(digits(n,s_m))%(n-1) == 0
  • Thank you for your return program. Did you find an error in my program? – Pruthviraj Jun 08 '20 at 12:41
  • Yes I did. After correction all the / into // it works just fine. Suppressed unneeded output version you can try online – Alexey Burdin Jun 08 '20 at 12:45
  • It has no output in either case, but if something goes wrong, the theoren prerequisite div would be true, not div would be false and the interpreter will have to check the second expression in assert not div or sum(rem_array)%(n-1)==0 -- and raise AssertionError if it is False, you can try it, there will be in 'debug' window of tio.run if you convert all the // back into / and rem_array.append(rem) back to rem_array.append(round(rem)). What was the programming language you learned before python? Pascal, I guess? Not many languages use round so wide as Pascal does. Thanks. – Alexey Burdin Jun 08 '20 at 12:54