Problem related to output in python programming (not gives expected result)

81 Views Asked by At

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

2

There are 2 best solutions below

3
On BEST ANSWER

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
0
On

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)