Grid method

mail@pastecode.io avatar
unknown
python
7 months ago
1.9 kB
6
Indexable
Never
def multiply(a, b):
    
	flag1 = False;
	flag2 = False;
	a = str(a)
	b = str(b)
	a = a.strip()
	b = b.strip()

	if (a[0] == '-') :
		a = a.replace("-", "");
		flag1 = True;
	
	if (b[0] == '-'):
		b = b.replace("-", "");
		flag2 = True;
	
	out1 = "";
	row = len(a);
	column = len(b);
	c =[ [0 for _ in range(column)] for __ in range(row)]
	for i in range(row):
		for j in range(column):
			n1 = int(a[i]);
			n2 = int(b[j]);
			c[i][j] = n1 * n2;
		
	sum1 = [0 for _ in range(row + column - 1)];
	m = 0;

	for i in range(row):
		k = i;
		add = 0;
		
		j = 0
		while j < column and k >= 0:
			add = add + c[k][j];
			j += 1
			k -= 1
		
		sum1[m] = add;
		m = m + 1;
	
	for k in range(1, column):
		i = row - 1;
		j = k;
		add = 0;
		while (j < column and i >= 0):
			add = add + c[i][j];
			j = j + 1;
			i = i - 1;
		
		sum1[m] = add;
		m = m + 1;
	
	if (len(sum1) != 1) :

		temp = str(sum1[len(sum1) - 1]);
		t = 0;

		for n in range(len(sum1) - 1, 0, -1):
			t = t + sum1[n];

			temp = str(t);
			if (len(temp) > 1) :

				str1 = temp[0 : len(temp) - 1]
				t = int(str1);
			
			else :
				t = 0;
			out1 = temp[len(temp) - 1] + out1;
		

		t = t + sum1[0];
		temp = str(t);
		out1 = temp + out1;
	
	else :
		out1 = out1 + sum1[0];
	

	s = out1

	for i in range(len(s) - 1):
		if (s[i] == '0') :
			s = s[:i] + s[i + 1:]
			i = i - 1;
		
		else :
			break;
		
	
	out1 = s

	if (out1 != "0"):
		if (flag1 == True and flag2 == False) :
			out1 = "-" + out1;
		
		elif (flag2 == True and flag1 == False) :
			out1 = "-" + out1;
		
	
	return out1;


str1 = int(123456789);
str2 = int(987654321);

print(multiply(str1, str2));

str1 = int(1235421415454545454545454544);
str2 = int(-1714546546546545454544548544544545);
print(multiply(str1, str2));

# This code is contributed by phasing17