0

here is my code... It's considering only 8 and 88 among 1 to 100 which aren't karpekar numbers...failing at if condition(s==n)

 def kaprekarNumbers(p, q):
  for i in range(p,q+1):
    n=i
    m=str(i*i);
    sl1=m[:int(len(m)/2)]
    sl2=m[int(len(m)/2):]
    if(sl2==""):
        sl2=0
    s=int(sl2)+int(sl2)
    print(s==n)
    if s==n:
        print(i)

1 Answers1

1

Using strings to process numbers is not usually a good idea.

You can get the number of digits of a number n with

math.ceil(math.log10(n))

You can get the last a digits of a number n with

n % a

(See: How does % work in Python?)

You can get the first a digits of a number n with

p // (10 ** a)

Those would be useful for base-10 Kaprekar numbers.

[Please note, I do not have a copy of Python to hand to check those.]

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84