Home > Blockchain >  Pronic numbers in python
Pronic numbers in python

Time:01-29

pronic numbers

Take a string in which random numbers are present and we have to find the product and the numbers(one is lesser and one is greater) which are already present in the string.also the numbers x and x 1 are single digit numbers. Let’s see the example

E.g. Given a string contains 1203456. The multiplication of 3 and 4(one is lesser and one is

greater) product become 12 and it’s present in the string. Like 4 and 5 (one is lesser and one is

greater) the product is 20 and it’s present in the string and so on.

In such a way, We have to find all the numbers and in the output, we have to display the pronic

numbers on a single line. Display only distinct numbers and make sure they are in sorted order.

If we haven’t found any product then print -1.

Example Input

1203456789

Output

0 2 6 12 20 56

import itertools
list1=[]
s=str(input())
res = [s[i: j] for i in range(len(s)) for j in range(i   1, len(s)   1)]
def pro(s1):
    set1=[]
    set2=[]
    for p in range(0,len(s1)-1):
        a=int(s1[p])
        b=int(s1[p 1])
        mul=int(a*b)
        mul=str(mul)
        if mul in res:
            set1.append(mul)
    if (len(set1)==0):
        print(-1)
    else:    
        print(*set1)
pro(s) 

my output is correct, out of 5 , only 2 test cases are failing ! can somebody help!?

CodePudding user response:

i would solve this problem by finding all the pronic numbers within range [0, n] with n being the number we got as input, then check if they are present in our number:

data = input() #1203456789
idata = int(data)

a,b = 0,1
res = []

while True:
    tmp=a*b
    a =1
    b =1
    if tmp > idata:
        break
    if str(tmp) in data:
        res.append(tmp)
if not res:
    res.append(-1)
print(*res) #0 2 6 12 20 56

CodePudding user response:

You haven't indicated what test cases are failing for you, but your approach looks overly complex -- it doesn't take very long to iterate over all the pronic numbers that might fit inside the input string, so just do that iteration and print all the numbers that match:

>>> from math import ceil, sqrt
>>> def find_pronics(s):
...     print(*(i*(i-1) for i in range(1, ceil(sqrt(int(s)))) if str(i*(i-1)) in s))
...
>>> find_pronics("1203456789")
0 2 6 12 20 56
  •  Tags:  
  • Related