Playing with digits codewar problem-looking for alternative way to solve this problem

  • Thread starter shivajikobardan
  • Start date
In summary, one way to solve the given problem is to express the given number as a sum of powers of its digits and check if the sum is divisible by the given number. This can be done using the equation N = Sum_of(Digit^Power) and a loop to calculate each digit's power. If the sum is divisible by the given number, the answer is the sum divided by the number, otherwise the answer is -1. A flowchart for this algorithm can also be used to understand the steps visually.
  • #1
shivajikobardan
674
54
Training on Playing with digits | Codewars
This is how I youtube'd and found a solution-:

Code:
n=89
p=1
my_sum=0
for num in str(n):
    my_sum=my_sum+(int(num))**p
    p=p+1
if(my_sum%n==0):
    print(int(my_sum/n))
else:
    print(-1)

What is another way to solve this problem? I prefer no code solutions with flowcharts/algorithms rather than writing codes so that I can try writing codes on my own. But I of course won't mind code with comments tbh.

I want a more mathematical way of solving this problem. like using that given equation in code and finding a solution...I know we are already using it...but I want sth different.
 
Technology news on Phys.org
  • #2
One way to solve this problem is to express the given number as a sum of powers of its digits. This can be done by using the following equation:N = Sum_of(Digit^Power)where, N is the given numberDigit is each digit of the given numberPower is the corresponding power for the digitWe can solve this problem by looping through each digit of the given number and calculate its corresponding power. For example, for the given number 89, we will get:89 = 8^1 + 9^2If the sum of the powers is divisible by the given number, then we have our answer. Otherwise, the answer is -1.A sample flowchart for this algorithm is given below:StartInput NSet Sum = 0Loop Through Each Digit of N Calculate Digit^Power Add to SumEnd LoopCheck if Sum is Divisible by N If Yes, Output Sum/N Else Output -1End
 

Similar threads

Back
Top