My assignment is to print out grey codes using recursion. A user puts in a bit value between 0-8, therefore the maximum amount of strings you can have is 256 (2^8).
I've got the base case done but i don't know what I would do for the else portion.
My code so far:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void gcodes (int n) {
char bits[256][8];
int i, j;
int x = pow (2, n);
if (n == 1) {
bits[0][0] = '0';
bits[1][0] = '1';
} else {
gcodes (n-1);
}
for (i=0; i<x; i++) {
for (j=0; j<n; j++) {
printf("%c", reverse[i][j]);
}
printf("\n");
}
}
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Invalid number of arguments\n");
return 0;
}
int n;
n = atoi (argv[1]);
if (n > 8 || n <= 0) {
printf("Invalid integer\n");
return 0;
}
gcodes (n);
}
a gray code can have only one bit change from one number to the next consecutive number. and over the whole sequence, there are no repeated values.
Given that criteria, there are several possible gray code implementations.
There are several deadend sequences where the values start off ok, then fail,
Calculating a gray code via code will take lots of experimentation.
In reality it is much easier to simply find a valid gray code sequence from the net, and paste that into any program that needs a gray code sequence.
Most often, a input is a gray coded wheel that is read to determine if the wheel moved rather than something generated in code.
however, if I were implementing a gray code generator, I would expect it to perform exclusive-or between the last generated value and the proposed new/next value and if that is valid (only one bit changed) I would search through the existing table of values to assure it is not a duplicate.
this SO question suggests a possible algorithm:
Non-recursive Grey code algorithm understanding
and the answer is repeated below:
The answer to all four your questions is that this algorithm does not start with lower values of n. All strings it generates have the same length, and the i-th (for i = 1, ..., 2n-1) string is generated from the (i-1)-th one.
Here is the first few steps for n = 4:
Start with G0 = 0000
To generate G1, flip 0-th bit in G0, as 0 is the position of the least significant 1 in the binary representation of 1 = 0001b. G1 = 0001.
To generate G2, flip 1-st bit in G1, as 1 is the position of the least significant 1 in the binary representation of 2 = 0010b. G2 = 0011.
To generate G3, flip 0-th bit in G2, as 0 is the position of the least significant 1 in the binary representation of 3 = 0011b. G3 = 0010.
To generate G4, flip 2-nd bit in G3, as 2 is the position of the least significant 1 in the binary representation of 4 = 0100b. G4 = 0110.
To generate G5, flip 0-th bit in G4, as 0 is the position of the least significant 1 in the binary representation of 5 = 0101b. G5 = 0111.
Since you define
char bits[256][8];
with automatic storage duration inside the function gcodes(), the array's lifetime ends when returning from the function, so you lose the results of the recursive calls. Thus, at least define it
static char bits[256][8];
or globally if you want to keep the resulting bits for use outside of gcodes().
Since in the standard Gray code the least significant bit (bit 0) follows the repetitive pattern of 0110, it is convenient to set the complete pattern in the base case even if it is not needed for n = 1.
For the ith code's bit j where j > 0, its value can be taken from bit j-1 of code i/2.
This leads to the completed function:
void gcodes(int n)
{
static char bits[256][8];
int i, j, x = pow(2, n);
if (n == 1)
{
bits[0][0] = '0';
bits[1][0] = '1';
bits[2][0] = '1';
bits[3][0] = '0';
}
else
{
gcodes(n-1);
// generate bit j (from n-1 down to 1) for codes up to x-1
for (i=0, j=n; --j; i=x/2)
for (; i<x; i++)
bits[i][j] = bits[i/2][j-1];
// replicate bit 0 for codes up to x-1
for (; i<x; i++)
bits[i][0] = bits[i%4][0];
}
for (i=0; i<x; i++, printf("\n"))
for (j=n; j--; )
printf("%c", bits[i][j]);
}
Related
I am very new to Coding. Here is a program that I wrote to convert decimal to binary
but there is one problem I am getting the result but it's in reverse
Example: Binary of 122 is 1111010 and I'm getting output 0101111.
Can anyone please tell me is it possible to reverse the output in my code?
Or what changes can I make in the following to get the correct output?
#include<stdio.h>
int main()
{
int n, q, r;
printf("Enter the decimal Number : ");
scanf("%d", &n);
int num=n;
while(n!=0)
{
r=n%2;
q=n/2;
printf("%d", r);
n=q;
}
return 0;
}
Seems like you are new to coding. It doesn't matter here is the problem.
Converting decimal to binary is like this,
eg:
division by 2
quotient
reminder
bit
10/2
5
0
0
5/2
2
1
1
2/2
1
0
2
1/2
0
1
3
=(1010)
So the output should have digits from bottom to top of the reminder column. Your output is printed from top to bottom.
See the code below where you need an array in order to store reminders and print the array in reverse order so you get the output you need
#include<stdio.h>
#include<stdlib.h>
int main(void){
int a[10],n,i;
printf("Enter the decimal Number : ");
scanf("%d",&n);
for(i=0;n>0;i++)
{
a[i]=n%2;
n=n/2;
}
printf("\nBinary of Given Number is=");
for(i=i-1;i>=0;i--)
{
printf("%d",a[i]);
}
return 0;
}
void display(unsigned n)
{
if(n == 0) return;
display(n /2);
printf("%d", n % 2);
}
and example usage:
https://godbolt.org/z/ahGPc74nf
As a homework: how to correctly handle 0?
Or not recursive version. This one can print or not leading zeroes:
void display(unsigned n, int printzeroes)
{
unsigned mask = 1 << (CHAR_BIT * sizeof(mask) - 1);
int print = printzeroes;
while(mask)
{
if(n & mask)
{
print = 1;
}
if(print) printf("%d", !!(n & mask));
mask >>= 1;
}
}
And usage: https://godbolt.org/z/7Eq71TMWb
First of all, please note that all numbers in a C program are to be regarded as binary. It's a common misconception among beginners that different number formats somehow co-exist in the executable program. But everything there is raw binary.
Sure the programmer may write numbers in different formats 7, 07 or 0x7 in the source code, but they get translated to binary by the compiler. Therefore, converting between binary and "x" doesn't make sense, because everything is already binary. You may however, convert from binary to a decimal string or similar, for the purpose of displaying a number to the user etc.
With that misconception out of the way - yes, you can create a binary string with the method you picked, dividing by ten and checking the remainder. The problem with that approach is that you'll get the most significant digit first. This is why you get the number backwards. So in order to do that, you'd have to store down the string in a character array first, before displaying it.
A more convenient way would be to use the "bitwise" operators like & and shift to mask out bit by bit in the data. Basically this:
if(n & (1u << bit)) // 1u to avoid shifting signed type
printf("1");
else
printf("0");
Where bit is the bit position 7,6,5... down to 0. If we prefer an up-counting loop instead, we can tweak the code into:
for(size_t i=0; i<8; i++)
{
size_t mask = 1u << 8-i-1;
...
}
And finally we can make the output a bit more compact, which is just a stylistic concern:
for(size_t i=0; i<8; i++)
{
size_t mask = 1u << 8-i-1;
printf("%c", n & mask ? '1' : '0');
}
If you aren't dead certain about C operator precedence, then use parenthesis, which is perfectly fine too:
for(size_t i=0; i<8; i++)
{
size_t mask = 1u << (8-i-1);
printf("%c", (n & mask) ? '1' : '0');
}
Here's the homework demanded by 0___________:
void printbin(int n)
{
static int depth;
if (n) ++depth, printbin(n / 2), --depth;
else if (depth) return; // print leading 0 only for n = 0
printf("%d", n % 2);
}
A leading 0 is not printed unless on the topmost recursion level.
You could maybe create an array of size 32 and keep adding the digits to the array. Or create a int variable and add the digits to the variable.
int result = 0;
while(n!=0)
{
r=n%2;
n=n/2;
result = result*10+r;
}
So i wanna do this C problem where i need to read N (0<=N<=20) and M( 0<=M<=10) then print all numeric palindromes formed with numbers from {1....N} and of length M.
Input:
N=15
M=3
Output:
1 2 1
2 2 2
3 2 3
...
11 3 11
...
Things like 12 3 12 are not considered palindrome.
I tried to find compress this this palindrome to be just a number but it shows me numbers that are not supposed to be palindroms to.
Can you give me some hints on how to do this? Or if you can help me do this it would be very nice.
I'm not sure if this is what you were looking for but to be honest the problem intrigued me so I created a rather simplistic brute-force approach to it. Hope you'll find it useful.
The logic is the following:
Create a function that will iterate through all possible numbers(not digits) for a given position in our array of numbers.
Make that function call itself recursively until there is one instance of it handling each position in our array of numbers.
The instance of the function that is handling the last(rightmost) number will check each combination of numbers for being a palindrome. If one is it will be printed out.
Ah yes, to determine if a given array of numbers is a palindrome I used the simple approach to transform the array of numbers into an array of digits. So, in other words single digit numbers are transferred as is BUT double digit ones get separated into two digits and transferred as two entries. Once I trans-coded the array of numbers into an array of digits I just run a simple algorithm that starts from both ends of the digits array moving towards the middle checking each pair for differences. If no difference is found the array of digits (and consequently the array of numbers it comes from) is a palindrome.
That is basically it.
I'll supply the code below. Hope I could help. If you need any clarification or have a comment (like if I totally missed the point of the question :)) just ask!
The code:
#include "stdint.h"
#include "stdbool.h"
#include "stdio.h"
#define NUMBER_ARRAY_SIZE (10UL)
#define DIGIT_ARRAY_SIZE (NUMBER_ARRAY_SIZE * 2UL)
bool isPalindrome(uint32_t numbers[], uint32_t lastIndex)
{
bool retVal = true;
uint32_t digits[DIGIT_ARRAY_SIZE];
int32_t digitsLastIndex = -1;
// Turn number-array into a digit-array.
for(uint32_t pos = 0u; pos <= lastIndex; pos++)
{
if(numbers[pos] < 10u)
{
// single digit => transfer it 1on1
digits[++digitsLastIndex] = numbers[pos];
}
else
{
// double digits => split in two digits
uint32_t firstDigit = numbers[pos]/10u;
uint32_t secondDigit = numbers[pos] - (firstDigit * 10u);
digits[++digitsLastIndex] = firstDigit;
digits[++digitsLastIndex] = secondDigit;
}
}
// This is where we check if we really have a palindrome formed by all the digits.
uint32_t numOfSteps = (digitsLastIndex + 1u) / 2u;
for(uint32_t i = 0u; i < numOfSteps; i++)
{
if(digits[i] != digits[digitsLastIndex - i])
{
retVal = false;
break;
}
}
return retVal;
}
void processNumberAtGivenPosition(uint32_t positionOfNumber, uint32_t lastAllowedPosition, uint32_t largestNumberAllowed, uint32_t numbers[])
{
// Generate and process all numbers in the actual position.
for (uint32_t number = 1u; number <= largestNumberAllowed; number++)
{
// Update the number-array with the actual number(at the actual position).
numbers[positionOfNumber] = number;
if(positionOfNumber == lastAllowedPosition)
{
// We are at the last position already. Check if the current number-array is a palindrome..
if(isPalindrome(numbers, lastAllowedPosition))
{
// ..if yes, then print it on the screen.
for (uint32_t i = 0u; i <= lastAllowedPosition; i++)
{
printf("%u", numbers[i]);
}
printf("\n");
}
}
else
{
// We still have more positions on the right. Move on to the next(->) one.
processNumberAtGivenPosition(positionOfNumber + 1u, lastAllowedPosition, largestNumberAllowed, numbers);
}
}
}
int main()
{
uint32_t N, M;
scanf("%u", &N);
scanf("%u", &M);
uint32_t numberArray[NUMBER_ARRAY_SIZE];
processNumberAtGivenPosition(0u, M - 1u, N, numberArray);
}
hoping for some help with bitwise operators. The exercise reads as following:
Write a function called bitpat_search() that looks for the occurence of a specified pattern of bits inside an unsigned int. The function should take three arguments, and should be called as such:
bitpat_search (source, pattern, n)
The function searches for the integer "source", starting at the leftmost bit, to see if the rightmost n bits of "pattern" occur in "source". If the pattern is found, have the function return the number of the bit at which the pattern begins, where the leftmost bit is number 0. If the pattern is not found, then have the function return -1. So, for example, the call
index = bitpat_search (0xe1f4, 0x5, 3);
causes the bit_pat(search() function to search the number 0xe1f4 (= 1110 0001 1111 0100 binary) for the occurence of the three-bit pattern 0x5 (= 101 binary). The function returns 11 to indicate that the pattern was found in the "source" beginning with bit number 11.
Make certain that the function makes no assumptions about the size of an int.
I've got a few problems getting this working:
1- The numbers don't actually make much sense to me... I've tried all kinds of printf() functions after each itiration, and it looks like the 0x5 number gets read as 100 binary, which would be four. If I try other numbers they just come fairly random, but often as 000, so.... not very helpful. Am I counting them wrong? Does the right shift change it somehow?
2 - it's returning the wrong position (19 rather than 11), but while I'm messing up the numbers as my q1 above, it's not really going to work, is it?
Sorry if this is obvious to all you lovely people, I just can see it. (I'm just trying to learn from the book btw, it's not homework from school).
Thanks
#include <stdio.h>
int int_size(unsigned int num);
int bit_test(unsigned int word, int position, int size);
int bitpat_search(unsigned int source, unsigned int pattern, int n);
int main(void)
{
int index;
index = bitpat_search(0xe1f4, 0x5, 3);
printf(" Pattern found in position %i\n", index);
return 0;
}
int bitpat_search(unsigned int source, unsigned int pattern, int n)
{
int i, j, tempSource, tempPat, count;
int size = int_size(~0);
for (i = 0; i < size;)
{
count = 0;
for (j = 0; j < n; j++)
{
tempSource = bit_test(source, i, size);
tempPat = bit_test(pattern, j, size);
i++;
count++;
if (tempSource != tempPat)
break;
}
if (count == n)
return i - n;
}
return 0;
}
int bit_test(unsigned int word, int position, int size)
{
if( (word >> (size - position)) & 0x1) // shift bits in word 31 minus n spaces right, and AND word with hexadecimal 1
return 1; // if above is true (1 & 1) return 1
else
return 0;
}
int int_size(unsigned int num)
{
int size = 0;
while (num)
{
size++;
num >>= 1;
}
return size;
}
for (i = 0; i < size;)
{
count = 0;
for (j = 0; j < n; j++)
{
tempSource = bit_test(source, i, size);
tempPat = bit_test(pattern, j, size);
Here, you're checking a bit at position i in the source against a bit at position j in the pattern. That needs to be i+j in the source, otherwise you compare a pattern against one bit, rather than a pattern against a number of bits, in the source. Since the pattern 101 contains ones and a zero, you'll never find anything.
Side note: you can replace the int_size function by sizeof(int)*8. That assumes 8-bit bytes, but computers for which that assumption does not hold haven't been made since the early eighties, so that should be a fairly safe assumption.
1- The numbers don't actually make much sense to me... I've tried all kinds of printf() functions after each itiration, and it looks like the 0x5 number gets read as 100 binary, which would be four. If I try other numbers they just come fairly random, but often as 000, so.... not very helpful. Am I counting them wrong?
I can't comment on code you've not presented, but of course hex 0x5 is binary 101. I'm inclined to suppose that in your tests you printed different values than you thought you were printing, or that your mechanism for printing them was flawed.
Does the right shift change it somehow?
Shift operators leave their operands unchanged. Of course, if the right-hand operand of a conforming shift operation is non-zero then the result differs from the left-hand operand. If the left-hand operand is drawn from a variable, then you might conceivably overwrite that variable's value afterward.
2 - it's returning the wrong position (19 rather than 11), but while I'm messing up the numbers as my q1 above, it's not really going to work, is it?
I don't think your main problem is "messing up the numbers". Your implementation is problematic. Consider the key loop nest in your code:
for (i = 0; i < size;)
{
count = 0;
for (j = 0; j < n; j++)
{
tempSource = bit_test(source, i, size);
tempPat = bit_test(pattern, j, size);
i++;
count++;
Observe that you increment the outer loop's control variable on each iteration of the inner loop. As a result, you test the pattern only against every nth starting index in the source string. That is, you test non-overlapping sets of the source bits. You should instead test the whole pattern starting at every possible starting position.
Note also that you test starting positions where an n-bit pattern cannot possibly start, on account of there being fewer than n bits between that position and the end of the source string. In this case you will end up invoking undefined behavior by using an invalid right-hand operand to a shift operator.
In the proposed algorithm, except the revealed issue by #WouterVerhelst, it exists other issues causing a wrong result.
Issue 1 - In the function bit_test(), the tested-bit is not the expected one.
To test a bit from the leftmost side, replace (size - position) by
(size - (position + 1)).
int bit_test(unsigned int word, int position, int size)
{
if( (word >> (size - (position + 1))) & 0x1) //
return 1; // if above is true (1 & 1) return 1
else
return 0;
}
Issue 2 - To be tested as the same size of source, the pattern shall be aligned to left.
In the bitpat_search(), before for-loop, shift-left of (size-n)
bits.
int size = int_size(source);
pattern = pattern << (size-n);
Issue 3 - To have the correct count to be compared with n, the comparison of bits with the break; should be done before count++.
if (tempSource != tempPat)
break;
count++;
Issue 4 - The index result returned would be i instead of i - n (linked with Issue 5).
if (count == n)
return (i); // instead of (i - n);
Issue 5 - As #WouterVerhelst suggests, the comparison between source and pattern should be done for each bit.
for (i = 0; i < size;i++) // each bit ==> i++
{
count = 0;
for (j = 0; j < n; j++)
{
tempSource = bit_test(source, i+j, size);
tempPat = bit_test(pattern, j, size);
// not here i++;
if (tempSource != tempPat)
break;
count++;
}
if (count == n)
return (i);
}
Issue 6 - And the result in case of 'pattern not found' is -1.
return (-1); // Instead of (0);
The problem statement is the following:
Given an integer array of n integers, find sum of bit differences in all pairs that can be formed from array elements. Bit difference of a pair (x, y) is count of different bits at same positions in binary representations of x and y.
For example, bit difference for 2 and 7 is 2. Binary representation of 2 is 010 and 7 is 111 ( first and last bits differ in two numbers).
Examples:
Input: arr[] = {1, 2}
Output: 4
All pairs in array are (1, 1), (1, 2)
(2, 1), (2, 2)
Sum of bit differences = 0 + 2 +
2 + 0
= 4
Based on this post the most efficient (running time of O(n)) solution is the following:
The idea is to count differences at individual bit positions. We traverse from 0 to 31 and count numbers with i’th bit set. Let this count be ‘count’. There would be “n-count” numbers with i’th bit not set. So count of differences at i’th bit would be “count * (n-count) * 2″.
// C++ program to compute sum of pairwise bit differences
#include <bits/stdc++.h>
using namespace std;
int sumBitDifferences(int arr[], int n)
{
int ans = 0; // Initialize result
// traverse over all bits
for (int i = 0; i < 32; i++)
{
// count number of elements with i'th bit set
int count = 0;
for (int j = 0; j < n; j++)
if ( (arr[j] & (1 << i)) )
count++;
// Add "count * (n - count) * 2" to the answer
ans += (count * (n - count) * 2);
}
return ans;
}
// Driver prorgram
int main()
{
int arr[] = {1, 3, 5};
int n = sizeof arr / sizeof arr[0];
cout << sumBitDifferences(arr, n) << endl;
return 0;
}
What I'm not entirely clear on is how the running time would be linear when there are two for loops incrementing by 1 for each iteration. The way I'm interpreting it is that since the outer loop is iterating from 0 to 32
(corresponding to the 0th and 32nd bits of each number) and because I'm guessing all 32 bit shifts would happen in the same clock period (or relatively fast compared to linear iteration), the overall running time would be dominated by the linear iteration over the array.
Is this the correct interpretation?
In English, "My algorithm runs in O(n) time" translates to "My algorithm runs in time that is at most proportional to n for very large inputs". The proportionality aspect of that is the reason that 32 iterations in an outer loop don't make any difference. The execution time is still proportional to n.
Let's look at a different example:
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
// do something
}
}
In this example the execution time is proportional to n2 so it's not O(n). It is however O(n2). And technically O(n3) and O(n4), ... as well. This follows from the definition.
There's only so much you can talk about this stuff in English without misinterpretation, so if you want to nail down the concepts you're best off checking out the formal definition in an introductory algorithms textbook or online class and working out a few examples.
Instead of comparing two numbers we could compare the i_th bit of every number with each other which would reduce your time complexity from O(n*n) to O(32*n), We just need to count the total pairs of zeroes and ones possible wrt i_th bit of every number.
Simple Cpp implementation would look like this:
int cntBits(vector<int> &A) {
int n = A.size();
int ans = 0;
for(int i=0;i<31;i++) {
long long z = 0,o = 0;
for(int j=0;j<n;j++) {
if( ((A[j]>>i)&1 ) == 1 ) o++;
else z++;
}
ans = ( ans + (z*o)%1000000007 )%1000000007;
}
return (2*ans)%1000000007;
}
Anyone who is feeling stuck over this logic can refer to this explanation: https://www.youtube.com/watch?v=OKROwC2fLEg
I'm trying to write a C program which performs multiplication of two numbers without directly using the multiplication operator, and it should take into account numbers which are sufficiently large so that even the usual addition of these two numbers cannot be performed by direct addition.
I was motivated for this when I was trying to (and successfully did) write a C program which performs addition using character strings, I did the following:
#include<stdio.h>
#define N 100000
#include<string.h>
void pushelts(char X[], int n){
int i, j;
for (j = 0; j < n; j++){
for (i = strlen(X); i >= 0; i--){
X[i + 1] = X[i];
}
X[0] = '0';
}
}
int max(int a, int b){
if (a > b){ return a; }
return b;
}
void main(){
char E[N], F[N]; int C[N]; int i, j, a, b, c, d = 0, e;
printf("Enter the first number: ");
gets_s(E);
printf("\nEnter the second number: ");
gets_s(F);
a = strlen(E); b = strlen(F); c = max(a, b);
pushelts(E, c - a); pushelts(F, c - b);
for (i = c - 1; i >= 0; i--){
e = d + E[i] + F[i] - 2*'0';
C[i] = e % 10; d = e / 10;
}
printf("\nThe answer is: ");
for (i = 0; i < c; i++){
printf("%d", C[i]);
}
getchar();
}
It can add any two numbers with "N" digits. Now, how would I use this to perform multiplication of large numbers? First, I wrote a function which performs the multiplication of number, which is to be entered as a string of characters, by a digit n (i.e. 0 <= n <= 9). It's easy to see how such a function is written; I'll call it (*). Now the main purpose is to multiply two numbers (entered as a string of characters) with each other. We might look at the second number with k digits (assuming it's a1a2.....ak) as:
a1a2...ak = a1 x 10^(k - 1) + a2 x 10^(k - 2) + ... + ak-1 x 10 + ak
So the multiplication of the two numbers can be achieved using the solution designed for addition and the function (*).
If the first number is x1x2.....xn and the second one is y1y2....yk, then:
x1x2...xn x y1y2...yk = (x1x2...xn) x y1 x 10^(k-1) + .....
Now the function (*) can multiply (x1x2...xn) with y1 and the multiplication by 10^(k-1) is just adding k-1 zero's next to the number; finally we add all of these k terms with each other to obtain the result. But the difficulty lies in just knowing how many digits each number contains in order to perform the addition each time inside the loop designed for adding them together. I have thought about doing a null array and each time adding to it the obtained result from multiplication of (x1x2....xn) by yi x 10^(i-1), but like I've said I am incapable of precising the required bounds and I don't know how many zeros I should each time add in front of each obtained result in order to add it using the above algorithm to the null array. More difficulty arises when I'll have to do several conversions from char types into int types and conversely. Maybe I'm making this more complicated than it should; I don't know if there's an easier way to do this or if there are tools I'm unaware of. I'm a beginner at programming and I don't know further than the elementary tools.
Does anyone have a solution or an idea or an algorithm to present? Thanks.
There is an algorithm for this which I developed when doing Small Factorials problem on SPOJ.
This algorithm is based on the elementary school multiplication method. In school days we learn multiplication of two numbers by multiplying each digit of the first number with the last digit of the second number. Then multiplying each digit of the first number with second last digit of the second number and so on as follows:
1234
x 56
------------
7404
+6170- // - is denoting the left shift
------------
69104
What actually is happening:
num1 = 1234, num2 = 56, left_shift = 0;
char_array[] = all digits in num1
result_array[]
while(num2)
n = num2%10
num2 /= 10
carry = 0, i = left_shift, j = 0
while(char_array[j])
i. partial_result = char_array[j]*n + carry
ii. partial_result += result_array[i]
iii. result_array[i++] = partial_result%10
iv. carry = partial_result/10
left_shift++
Print the result_array in reverse order.
You should note that the above algorithm work if num1 and num2 do not exceed the range of its data type. If you want more generic program, then you have to read both numbers in char arrays. Logic will be the same. Declare num1 and num2 as char array. See the implementation:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char num1[200], num2[200];
char result_arr[400] = {'\0'};
int left_shift = 0;
fgets(num1, 200, stdin);
fgets(num2, 200, stdin);
size_t n1 = strlen(num1);
size_t n2 = strlen(num2);
for(size_t i = n2-2; i >= 0; i--)
{
int carry = 0, k = left_shift;
for(size_t j = n1-2; j >= 0; j--)
{
int partial_result = (num1[j] - '0')*(num2[i] - '0') + carry;
if(result_arr[k])
partial_result += result_arr[k] - '0';
result_arr[k++] = partial_result%10 + '0';
carry = partial_result/10;
}
if(carry > 0)
result_arr[k] = carry +'0';
left_shift++;
}
//printf("%s\n", result_arr);
size_t len = strlen(result_arr);
for(size_t i = len-1; i >= 0; i-- )
printf("%c", result_arr[i]);
printf("\n");
}
This is not a standard algorithm but I hope this will help.
Bignum arithmetic is hard to implement efficiently. The algorithms are quite hard to understand (and efficient algorithms are better than the naive one you are trying to implement), and you could find several books on them.
I would suggest using an existing Bignum library like GMPLib or use some language providing bignums natively (e.g. Common Lisp with SBCL)
You could re-use your character-string-addition code as follows (using user300234's example of 384 x 56):
Set result="0" /* using your character-string representation */
repeat:
Set N = ones_digit_of_multiplier /* 6 in this case */
for (i = 0; i < N; ++i)
result += multiplicand /* using your addition algorithm */
Append "0" to multiplicand /* multiply it by 10 --> 3840 */
Chop off the bottom digit of multiplier /* divide it by 10 --> 5 */
Repeat if multiplier != 0.