You are here : InfyTQ Archive >> InfyTQ Coding Problems
Given a string of random numbers, your job is to find the product of the numbers(one is lesser and one is greater) who is already present in the string.
For instance, a pronic number is a number which is the product of two consecutive integers, that is, a number of the form n(n + 1). Like 6 is the pronic number as 2*3 = 6.
Input :
First Input : String of random numbers
Output : List of pronic numbers
Sample Testcases :
I/P 1:
123456
O/P 1:
[2,6,12]
I/P 2:
4567
O/P 2:
-1
Solution :
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 pronic(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)
pronic((s))
According to the question number can be selected from anywhere else from the string, but in the solution you selected the adjacent elements and multiply this and check for the multiplication in the string
but we can select the numbers from anywhere the string so one approch is to sort the numbers and then apply above solution.
or the question is about to select the adjacent element only? Please guide as we are very confused.
check in geeks for geeks finding sqrt see it once
can you please provide java solution also ?
import java.io.*;
import java.util.*;
import java.util.stream.*;
import java.util.function.*;
public class Solution {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
Listss=new ArrayList();
String s=in.nextLine();
for (int i = 0; i < s.length(); i++){
for (int j = i+1; j <= s.length(); j++){
ss.add(s.substring(i,j));
}
}List li = ss.stream().map(Integer::parseInt).collect(Collectors.toList());
//System.out.println(li);
//Mapmap=new TreeMap();
HashSetfin =new HashSet();
for(int i=0;i<li.size();i++){
int d=li.get(i);
int k=(int)Math.sqrt(d);
if((k)*(k+1)==d && d!=0){
//if(map.containsKey(d)){
// int val=map.get(d);
// map.put(d,val+1);
//}else{
// map.put(d,1);
//}
//System.out.print(d+",");
fin.add(d);
}
}List list = new ArrayList(fin);
Collections.sort(list);
int si=list.size();
int j=0;
if(si>0){
for(int i=0;i<si;i++){
System.out.print(list.get(i));
j++;
if(j!=si){
System.out.print(",");
}
}
}else{
System.out.println("-1");
}
/*int i=0;
for(Map.Entry m : map.entrySet()){
System.out.print(m.getKey());
i++;
if(i!=map.size())
System.out.print(",");
}*/
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
}
}