divinesouljoy commited on
Commit
2f12c1e
·
verified ·
1 Parent(s): 34f5dd0

Upload vedic_multiplier.cpp with huggingface_hub

Browse files
Files changed (1) hide show
  1. vedic_multiplier.cpp +74 -0
vedic_multiplier.cpp ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <iostream>
2
+ #include <vector>
3
+ #include <algorithm>
4
+
5
+ // Function to implement Urdhva-Tiryagbhyam (Vedic Multiplication)
6
+ // This simplified version handles two positive integers.
7
+ int vedic_multiply(int num1, int num2) {
8
+ std::string s_num1 = std::to_string(num1);
9
+ std::string s_num2 = std::to_string(num2);
10
+
11
+ // Pad with leading zeros if lengths are different
12
+ int len1 = s_num1.length();
13
+ int len2 = s_num2.length();
14
+ int max_len = std::max(len1, len2);
15
+
16
+ // Reverse strings for easier right-to-left processing
17
+ std::reverse(s_num1.begin(), s_num1.end());
18
+ std::reverse(s_num2.begin(), s_num2.end());
19
+
20
+ // Store digits as integers
21
+ std::vector<int> n1_digits(max_len, 0);
22
+ std::vector<int> n2_digits(max_len, 0);
23
+
24
+ for (int i = 0; i < len1; ++i) n1_digits[i] = s_num1[i] - '0';
25
+ for (int i = 0; i < len2; ++i) n2_digits[i] = s_num2[i] - '0';
26
+
27
+ std::vector<int> result_digits(2 * max_len, 0);
28
+ int carry = 0;
29
+
30
+ for (int i = 0; i < 2 * max_len - 1; ++i) {
31
+ int sum = carry;
32
+ for (int j = 0; j <= i; ++j) {
33
+ if (j < max_len && (i - j) < max_len) {
34
+ sum += n2_digits[j] * n1_digits[i - j];
35
+ }
36
+ }
37
+ result_digits[i] = sum % 10;
38
+ carry = sum / 10;
39
+ }
40
+ result_digits[2 * max_len - 1] = carry;
41
+
42
+ std::string result_str = "";
43
+ // Find the first non-zero digit from the right (most significant) for final result
44
+ int first_digit_idx = 2 * max_len - 1;
45
+ while (first_digit_idx > 0 && result_digits[first_digit_idx] == 0) {
46
+ first_digit_idx--;
47
+ }
48
+
49
+ for (int i = first_digit_idx; i >= 0; --i) {
50
+ result_str += std::to_string(result_digits[i]);
51
+ }
52
+
53
+ if (result_str.empty()) return 0;
54
+ return std::stoi(result_str);
55
+ }
56
+
57
+ int main() {
58
+ int a = 12;
59
+ int b = 13;
60
+ int result = vedic_multiply(a, b);
61
+ std::cout << "Vedic Multiplication of " << a << " and " << b << " = " << result << std::endl;
62
+
63
+ a = 99;
64
+ b = 88;
65
+ result = vedic_multiply(a, b);
66
+ std::cout << "Vedic Multiplication of " << a << " and " << b << " = " << result << std::endl;
67
+
68
+ a = 123;
69
+ b = 456;
70
+ result = vedic_multiply(a, b);
71
+ std::cout << "Vedic Multiplication of " << a << " and " << b << " = " << result << std::endl;
72
+
73
+ return 0;
74
+ }