How to multiply two arrays with each element as a digit c++ - c++

I am going to have an array that is 50 elements long. Each element will contain one digit to form a 50 digit number. What I want to do is multiply this 50 digit long array by another 50 digit long array. The way I thought of doing this was converting each number to form one string. Then produce an algorithm that would multiply line by line 20 digits at a time. Then once the last for loop breaks out of scope, I could reconstruct the new array, digit by digit from converting it from a string. Any alternate ideas before I attempt this, or is what I got what you would do too?

int n1[50], n2[50], out[51];
// n1 and n2 must be populated here
int carry = 0;
for (int cur = 49; cur >= 0; --cur) {
out[cur+1] = n1[cur] * n2[cur] + carry;
carry = out[cur+1] / 10;
out[cur+1] %= 10;
}
out[0] = carry;

I believe you could find the question at leetcode OJ named "Multiply Strings".
This is my solution. Just for reference. Wish this will help :)
class Solution {
public:
string multiply(string num1, string num2) {
int s1(num1.size()), s2(num2.size()), size(s1+s2);
vector<int> digit(size,0), carry(size,0); // digit: store current digit, carry: store carry digit
for(int i = 0; i < s1; ++i){
for(int j = 0; j < s2; ++j){
int mul = num1[s1-1-i]-'0';
int muled = num2[s2-1-j]-'0';
int tmp = mul*muled;
digit[size-1-i-j] += tmp%10; // accum
carry[size-1-i-j-1] += tmp/10; // accum
}
}
int carrFlag(0); // initial carry_flag
for(int i = size-1; i >= 0; --i){ // merge digit and carry
int sum = digit[i] + carry[i] + carrFlag;
ret.insert(ret.begin(),1,'0'+sum%10); // compose result string
carrFlag = sum/10; // update carry_flag
}
int pos(0);
while(ret[pos] == '0') ++pos; // get rid of extra 0's
if(pos>=size) return "0"; // edge case
return ret.substr(pos);
}
private:
string ret;
};

Related

Explaining C++ code for adding two strings

I'm trying to solve the following problem, which how to add two strings without converting them to integer. I have found a solution to the problem, but I don't understand it. Would someone explain it in plain english please ?
here is the code :
class Solution {
public:
string addStrings(string num1, string num2) {
int i=num1.size()-1,j=num2.size()-1,carry=0;
string res="";
while(i>=0||j>=0)
{
if(i>=0) carry+=num1[i--]-'0';
if(j>=0) carry+=num2[j--]-'0';
res=to_string(carry%10)+res;
carry/=10;
}
return carry?"1"+res:res;
}
};
Okay! Lemme explain to you. Numbers are from 0-9. So, maximum sum possible is <=18. So, we need to take a flag/count/carry dummy variable which will be 1 when our sum exceeds 10 (num1[i]-'0'+num2[i]-'0'>=10).
When we add two numbers we start from the end. Same here we will loop from end to start i.e. while(i>=0 or j>=0 or count). Count is in while statement 'coz what if i=0 &/| j=0 sum is more than 10 then we will need to add an extra one to the start of the string.
Add elements from both strings and decrement corresponding counter i--, j--. Add carry either 0 or 1. calculate new carry which will be passed on to the next sum calculation. Take modulo of sum as we want a single digit. Covert it into string and append to res.
My Code
class Solution {
public:
string addStrings(string num1, string num2) {
int n1 = num1.size(), i = n1 - 1;
int n2 = num2.size(), j = n2 - 1;
int carry = 0;
string res = "";
while(i>=0 || j>=0 || carry){
long sum = 0;
if(i >= 0){sum += (num1[i] - '0');i--;}
if(j >= 0){sum += (num2[j] - '0');j--;}
sum += carry;
carry = sum / 10;
sum = sum % 10;
res = to_string(sum) + res;
}
return res;
}
};

How can I convert a string to an int in c++ when I'm not using a standard string?

I'm building my own string class and I'm trying to use this function to convert a numerical string to an integer:
int String::convertToInt() const {
int exp = length() - 1;
int result = 0;
for(int i = 0; i < length(); ++i) {
result += (charAt(i) - '0') * (10 ^ exp);
--exp;
}
return result;
}
Something isn't working right, but I can't pick out what it is. When I try to convert "49" to an int, it converts it to 134.
^ is XOR. I believe you're looking for std::pow(10, exp).
Or even this:
int String::convertToInt() const {
int order = std::pow(10, length() - 1);
int result = 0;
for(int i = 0; i < length(); ++i) {
result += (charAt(i) - '0') * order;
order /= 10;
}
return result;
}
The easiest way is to realize that 49 is 4 * 10 + 9, and 493 similarly is 49 * 10 + 3.
That is to say, the result is 10 times the first N-1 digits plus the last digit. You can write that as a loop or as a recursive function. Stack depth won't hurt you; after about 20 digits you'd overflow even a 64 bits result. So
int String::convertToInt() const {
if (empty()) return 0; // Recursive functions better terminate.
// TODO: negative numbers.
return 10 * convertToInt(substr(0, length()-1)) + (back() - '0');
}
or
int String::convertToInt() const {
// TODO: negative numbers.
int result = 0;
for(int i = 0; i < length(); ++i) {
result * = 10;
result += (charAt(i) - '0');
}
return result;
}
A more efficient approach would be:
// I know you said you are using something else
// but the same principle applies here
std::string s = "12345";
unsigned int result = 0;
unsigned int place = 1;
for (std::size_t i = s.length() - 1; i >= 0; --i, place *= 10)
{
result += (s[i] - '0') * place;
}
Basically, you start at the right-most character and work your way left. Each character you move left, you multiply your place by 10 (very similar to how most of us learned to do addition growing up: add your 1's ... add your 10's ... add your 100's ... etc.). This also assumes that you already know the string contains nothing but numeric characters ('0'-'9').

converting a string (containing numbers) into an integer and returning that integer

i'm working on a code right now in C++, in which i'm supposed to make a function which receives a string of numbers and converts it into an integer then returns that value. for example if i pass "4569" as string, it will return 4569 integer value.
can anyone help me point out where i'm wrong ??? thanks in advance :)
#include<iostream>
#include<cstdlib>
using namespace std;
void getInput(char arr[] , int size )
{
cout<<"ENTER THE ARRAY"<<endl;
cin.getline(arr,size);
}
int stringToInteger(char source[])
{
int sum = 0;
int y=strlen(source);
int multiply = 1;
for( int i=y ; i>=0 ; i--)
{
int n= source[i];
sum = (sum + (n * multiply));
multiply = (multiply *10);
}
return sum;
}
int main()
{
const int size =100;
char inputArr [size];
getInput (inputArr, size );
int x = stringToInteger (inputArr );
cout<<"THE RETURNED INTEGER VALUE IS"<<endl;
cout<<x<<endl;
return 0;
}
First, you're starting at the character after the end of the string. If the length (returned by strlen) is y, then valid indexes are 0 <= i < y. So your loop wants to start from y-1.
for( int i=y-1 ; i>=0 ; i--)
^^
Then, you need to convert each ASCII digit into a value from 0 to 9, by subtracting the ASCII value for '0':
int n= source[i] - '0';
^^^^^
Then you should probably detect and handle erroneous input, including values that are too large to be represented by int.
Then, once you've learnt how to implement this in C, throw it away and use the C++ library:
std::string input;
std::getline(std::cin, input);
int x = std::stoi(input);
Try,
#include <stdlib.h>
and in your main():
int x = atoi(inputArr);
I'm not sure why you aren't using atoi or std::stoi, but your algorithm has a logical flaw:
int stringToInteger(char source[])
{
int sum = 0;
int y=strlen(source);
int multiply = 1;
for(int i=y - 1; i >= 0; i--) // you were starting at y, which is 1 passed the end of the array
{
int n = (int)(source[i] - '0');
sum += (n * multiply); // += makes this more readable
multiply *= 10; // same with *=
}
return sum;
}
That said, if this was something other than a homework assignment, you should be using the solutions posted https://stackoverflow.com/a/18238566/529761 or https://stackoverflow.com/a/18238682/529761 (depending on your language requirements).
Also, even this change has 1 potential problem: If the source contains non-numeric characters, it will not work properly. A simple way to approach it is to break out if you encounter a character that shouldn't be there:
int stringToInteger(char source[])
{
int sum = 0;
int y=strlen(source);
int multiply = 1;
for(int i=y - 1; i >= 0; i--) // you were starting at y, which is 1 passed the end of the array
{
int n = (int)(source[i] - '0');
if (n < 0 || n > 9)
break;
sum += (n * multiply); // += makes this more readable
multiply *= 10; // same with *=
}
return sum;
}
No need to call a strlen -- until you are allowed to use library functions (the above-mentioned atoi and strtol), you can use this:
int stringToInteger(char *source)
{
int sum = 0;
if (source)
while (*source >= '0' && *source <= '9')
{
sum = 10*sum + *source - '0';
source++;
}
return sum;
}
As implied in about every other answer, you forgot there is a difference between the ASCII character '0' and the binary value 0.

To find the longest substring with equal sum in left and right in C++

I was solving a question, with which I am having some problems:
Complete the function getEqualSumSubstring, which takes a single argument. The single argument is a string s, which contains only non-zero digits.
This function should print the length of longest contiguous substring of s, such that the length of the substring is 2*N digits and the sum of the leftmost N digits is equal to the sum of the rightmost N digits. If there is no such string, your function should print 0.
int getEqualSumSubstring(string s) {
int i=0,j=i,foundLength=0;
for(i=0;i<s.length();i++)
{
for(j=i;j<s.length();j++)
{
int temp = j-i;
if(temp%2==0)
{
int leftSum=0,rightSum=0;
string tempString=s.substr(i,temp);
for(int k=0;k<temp/2;k++)
{
leftSum=leftSum+tempString[k]-'0';
rightSum=rightSum+tempString[k+(temp/2)]-'0';
}
if((leftSum==rightSum)&&(leftSum!=0))
if(s.length()>foundLength)
foundLength=s.length();
}
}
}
return(foundLength);
}
The problem is that this code is working for some samples and not for the others. Since this is an exam type question I don't have the test cases either.
This code works
int getEqualSumSubstring(string s) {
int i=0,j=i,foundLength=0;
for(i=0;i<s.length();i++)
{
for(j=i;j<s.length();j++)
{
int temp = j-i+1;
if(temp%2==0)
{
int leftSum=0,rightSum=0;
string tempString=s.substr(i,temp);
// printf("%d ",tempString.length());
for(int k=0;k<temp/2;k++)
{
leftSum=leftSum+tempString[k]-48;
rightSum=rightSum+tempString[k+(temp/2)]-48;
}
if((leftSum==rightSum)&&(leftSum!=0))
if(tempString.length()>foundLength)
foundLength=tempString.length();
}
}
}
return(foundLength);
}
The temp variable must be j-i+1. Otherwise the case where the whole string is the answer will not be covered. Also, we need to make the change suggested by Scott.
Here's my solution that I can confirm works. The ones above didn't really work for me - they gave me compile errors somehow. I got the same question on InterviewStreet, came up with a bad, incomplete solution that worked for 9/15 of the test cases, so I had to spend some more time coding afterwards.
The idea is that instead of caring about getting the left and right sums (which is what I initially did as well), I will get all the possible substrings out of each half (left and right half) of the given input, sort and append them to two separate lists, and then see if there are any matches.
Why?
Say the strings "423" and "234" have the same sum; if I sorted them, they would both be "234" and thus match. Since these numbers have to be consecutive and equal length, I no longer need to worry about having to add them up as numbers and check.
So, for example, if I'm given 12345678, then on the left side, the for-loop will give me:
[1,12,123,1234,2,23,234,3,34]
And on the right:
[5,56,567,5678,...]
And so forth.
However, I'm only taking substrings of a length of at least 2 into account.
I append each of these substrings, sorted by converting into a character array then converting back into a string, into ArrayLists.
So now that all this is done, the next step is to see if there are identical strings of the same numbers in these two ArrayLists. I simply check each of temp_b's strings against temp_a's first string, then against temp_a's second string, and so forth.
If I get a match (say, "234" and "234"), I'll set the length of those matching substrings as my tempCount (tempCount = 3). I also have another variable called 'count' to keep track of the greatest length of these matching substrings (if this was the first occurrence of a match, then count = 0 is overwritten by tempCount = 3, so count = 3).
As for the odd/even string length with the variable int end, the reason for this is because in the line of code s.length()/2+j, is the length of the input happened to be 11, then:
s.length() = 11
s.length()/2 = 11/5 = 5.5 = 5
So in the for-loop, s.length()/2 + j, where j maxes out at s.length()/2, would become:
5 + 5 = 10
Which falls short of the s.length() that I need to reach for to get the string's last index.
This is because the substring function requires an end index of one greater than what you'd put for something like charAt(i).
Just to demonstrate, an input of "47582139875" will generate the following output:
[47, 457, 4578, 24578, 57, 578, 2578, 58, 258, 28] <-- substrings from left half
[139, 1389, 13789, 135789, 389, 3789, 35789, 789, 5789, 578] <-- substrings from right half
578 <-- the longest one that matched
6 <-- the length of '578' x 2
public static int getEqualSumSubtring(String s){
// run through all possible length combinations of the number string on left and right half
// append sorted versions of these into new ArrayList
ArrayList<String> temp_a = new ArrayList<String>();
ArrayList<String> temp_b = new ArrayList<String>();
int end; // s.length()/2 is an integer that rounds down if length is odd, account for this later
for( int i=0; i<=s.length()/2; i++ ){
for( int j=i; j<=s.length()/2; j++ ){
// only account for substrings with a length of 2 or greater
if( j-i > 1 ){
char[] tempArr1 = s.substring(i,j).toCharArray();
Arrays.sort(tempArr1);
String sorted1 = new String(tempArr1);
temp_a.add(sorted1);
//System.out.println(sorted1);
if( s.length() % 2 == 0 )
end = s.length()/2+j;
else // odd length so we need the extra +1 at the end
end = s.length()/2+j+1;
char[] tempArr2 = s.substring(i+s.length()/2, end).toCharArray();
Arrays.sort(tempArr2);
String sorted2 = new String(tempArr2);
temp_b.add(sorted2);
//System.out.println(sorted2);
}
}
}
// For reference
System.out.println(temp_a);
System.out.println(temp_b);
// If the substrings match, it means they have the same sum
// Keep track of longest substring
int tempCount = 0 ;
int count = 0;
String longestSubstring = "";
for( int i=0; i<temp_a.size(); i++){
for( int j=0; j<temp_b.size(); j++ ){
if( temp_a.get(i).equals(temp_b.get(j)) ){
tempCount = temp_a.get(i).length();
if( tempCount > count ){
count = tempCount;
longestSubstring = temp_a.get(i);
}
}
}
}
System.out.println(longestSubstring);
return count*2;
}
Heres my solution to this question including tests. I've added an extra function just because I feel it makes the solution way easier to read than the solutions above.
#include <string>
#include <iostream>
using namespace std;
int getMaxLenSumSubstring( string s )
{
int N = 0; // The optimal so far...
int leftSum = 0, rightSum=0, strLen=s.size();
int left, right;
for(int i=0;i<strLen/2+1;i++) {
left=(s[i]-int('0')); right=(s[strLen-i-1]-int('0'));
leftSum+=left; rightSum+=right;
if(leftSum==rightSum) N=i+1;
}
return N*2;
}
int getEqualSumSubstring( string s ) {
int maxLen = 0, substrLen, j=1;
for( int i=0;i<s.length();i++ ) {
for( int j=1; j<s.length()-i; j++ ) {
//cout<<"Substring = "<<s.substr(i,j);
substrLen = getMaxLenSumSubstring(s.substr(i,j));
//cout<<", Len ="<<substrLen;
if(substrLen>maxLen) maxLen=substrLen;
}
}
return maxLen;
}
Here are a few tests I ran. Based upon the examples above they seem right.
int main() {
cout<<endl<<"Test 1 :"<<getEqualSumSubstring(string("123231"))<<endl;
cout<<endl<<"Test 2 :"<<getEqualSumSubstring(string("986561517416921217551395112859219257312"))<<endl;
cout<<endl<<"Test 3:"<<getEqualSumSubstring(string("47582139875"))<<endl;
}
Shouldn't the following code use tempString.length() instead of s.length()
if((leftSum==rightSum)&&(leftSum!=0))
if(s.length()>foundLength)
foundLength=s.length();
Below is my code for the question... Thanks !!
public class IntCompl {
public String getEqualSumSubstring_com(String s)
{
int j;
int num=0;
int sum = 0;
int m=s.length();
//calculate String array Length
for (int i=m;i>1;i--)
{
sum = sum + m;
m=m-1;
}
String [] d = new String[sum];
int k=0;
String ans = "NULL";
//Extract strings
for (int i=0;i<s.length()-1;i++)
{
for (j=s.length();j>=i+1;k++,j--)
{
num = k;
d[k] = s.substring(i,j);
}
k=num+1;
}
//Sort strings in such a way that the longest strings precede...
for (int i=0; i<d.length-1; i++)
{
for (int h=1;h<d.length;h++)
{
if (d[i].length() > d[h].length())
{
String temp;
temp=d[i];
d[i]=d[h];
d[h]=temp;
}
}
}
// Look for the Strings with array size 2*N (length in even number) and such that the
//the sum of left N numbers is = to the sum of right N numbers.
//As the strings are already in decending order, longest string is searched first and break the for loop once the string is found.
for (int x=0;x<d.length;x++)
{
int sum1=0,sum2=0;
if (d[x].length()%2==0 && d[x].length()<49)
{
int n;
n = d[x].length()/2;
for (int y=0;y<n;y++)
{
sum1 = sum1 + d[x].charAt(y)-'0';
}
for (int y=n;y<d[x].length();y++)
{
sum2 = sum2 + d[x].charAt(y)-'0';
}
if (sum1==sum2)
{
ans = d[x];
break;
}
}
}
return ans;
}
}
Here is the complete Java Program for this question.
Complexity is O(n^3)
This can however be solved in O(n^2).For O(n^2) complexity solution refer to this link
import java.util.Scanner;
import static java.lang.System.out;
public class SubStringProblem{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
out.println("Enter the Digit String:");
String s = sc.nextLine();
int n = (new SubStringProblem()).getEqualSumSubString(s);
out.println("The longest Sum SubString is "+n);
}
public int getEqualSumSubString(String s){
int N;
if(s.length()%2==0)
{
//String is even
N = s.length();
}
else{
//String is odd
N=s.length()-1;
}
boolean flag =false;
int sum1,sum2;
do{
for(int k=0;k<=s.length()-N;k++){
sum1=0;
sum2=0;
for(int i =k,j=k+N-1;i<j;i++,j--)
{
sum1=sum1 + Integer.parseInt(s.substring(i,i+1));
sum2+=Integer.parseInt(s.substring(j,j+1));
}
if(sum1==sum2){
return N;
}
}
N-=2;
flag =true;
}while(N>1);
return -1;
}
}
What is your rationale for the number 48 on these two lines?
for(int k=0;k<temp/2;k++)
{
leftSum=leftSum+tempString[k]-48;
rightSum=rightSum+tempString[k+(temp/2)]-48;
}
I am just overly curious and would like to hear the reasoning behind it, because I have a similar solution, but without the 48 and it still works. However, I added the 48 an still got the correct answer.
Simple solution. O(n*n). s - input string.
var longest = 0;
for (var i = 0; i < s.length-1; i++) {
var leftSum = rightSum = 0;
for (var j = i, k = i+1, l = 2; j >=0 && k < s.length; j--, k++, l+=2) {
leftSum += parseInt(s[j]);
rightSum += parseInt(s[k]);
if (leftSum == rightSum && l > longest) {
longest = l;
}
}
}
console.log(longest);

How can I make my implementation of Project Euler 25 faster, so I can actually compute the answer?

Here is my implementation of Problem 25 - Project Euler (see comments in code for explanation of how it works):
#include <iostream> //Declare headers and use correct namespace
#include <math.h>
using namespace std;
//Variables for the equation F_n(newTerm) = F_n-1(prevTerm) + Fn_2(currentTerm)
unsigned long long newTerm = 0;
unsigned long long prevTerm = 1; //F_1 initially = 1
unsigned long long currentTerm = 1; //F_2 initially = 2
unsigned long long termNo = 2; //Current number for the term
void getNextTerms() { //Iterates through the Fib sequence, by changing the global variables.
newTerm = prevTerm + currentTerm; //First run: newTerm = 2
unsigned long long temp = currentTerm; //temp = 1
currentTerm = newTerm; //currentTerm = 2
prevTerm = temp; //prevTerm = 1
termNo++; //termNo = 3
}
unsigned long long getLength(unsigned long long number) //Returns the length of the number
{
unsigned long long length = 0;
while (number >= 1) {
number = number / 10;
length++;
}
return length;
}
int main (int argc, const char * argv[])
{
while (true) {
getNextTerms(); //Gets next term in the Fib sequence
if (getLength(currentTerm) < 1000) { //Checks if the next terms size is less than the desired length
}
else { //Otherwise if it is perfect print out the term.
cout << termNo;
break;
}
}
}
This works for the example, and will run quickly as long as this line:
if (getLength(currentTerm) < 1000) { //Checks if the next term's size is less than the desired length
says 20 or lower instead of 1000. But if that number is greater than 20 it takes a forever, my patience gets the better of me and I stop the program, how can I make this algorithm more efficient?
If you have any questions just ask in the comments.
There is a closed formula for the Fibonachi numbers (as well as for any linear recurrent sequence).
So F_n = C1 * a^n + C2 * b^n, where C1, C2, a and b are numbers that can be found from the initial conditions, i.e. for the Fib case from
F_n+2 = F_n+1 + F_n
F_1 = 1
F_2 = 1
I don't give their values on purpose here. It's just a hint.
nth fibonacci number is =
(g1^n-g2^n)/sqrt(5).
where g1 = (1+sqrt(5))/2 = 1.61803399
g2 = (1-sqrt(5))/2 = -0.61803399
For finding the length of nth fibonacci number, we can just calculate the log(nth fibonacci number).So, length of nth fibonacci number is,
log((g1^n-g2^n)/sqrt(5)) = log(g1^n-g2^n)-0.5*log(5).
you can just ignore g2^n, since it is very small negative number.
Hence, length of nth fibonacci is
n*log(g1)-0.5*log(5)
and we need to find the smallest value of 'n' such that this length = 1000, so we can find the value of n for which the length is just greater than 999.
So,
n*log(g1)-0.5*log(5) > 999
n*log(g1) > 999+0.5*log(5)
n > (999+0.5*log(5))/log(g1)
n > (999.3494850021680094)/(0.20898764058551)
n > 4781.859263075
Hence, the smallest required n is 4782. No use of any coding, easiest way.
Note: everywhere log is used in base 10.
This will probably speed it up a fair bit:
int getLength(unsigned long long number) //Returns the length of the number when expressed in base-10
{
return (int)log10(number) + 1;
}
...but, you can't reach 1000 digits using an unsigned long long. I suggest looking into arbitrary-precision arithmetic libraries, or languages which have arbitrary-precision arithmetic built in.
You could try computing a Fibonacci number using matrix exponentiation. Then repeated doubling to get to a number that has more than 1000 digits and use binary search in that range to find the first one.
using doubles, you can come to a solution knowing the highest exponential is 308:
get the sequence to the exp of 250, then divide your two numbers by 1e250. Restart the algorithm with those two numbers
if you do this 4 times, you'll get the right answer
C++ code maybe as follows:
#include "iostream"
#include "string.h"
#include "algorithm"
using namespace std;
string addTwoString(string a, string b)
{
if (a.length() == 0)
{
return b;
}
if (b.length() == 0)
{
return a;
}
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
string result = "";
string str_1, str_2;
if (a.length() > b.length())
{
str_1 = b;
str_2 = a;
}
else
{
str_1 = a;
str_2 = b;
}
int index = 0;
int value = 0, over_value = 0;
for (; index < str_1.length(); ++index)
{
int temp_1 = (int)(str_1[index] - '0');
int temp_2 = (int)(str_2[index] - '0');
int temp = temp_1 + temp_2 + over_value;
value = temp % 10;
over_value = temp / 10;
char c = (char)(value + '0');
result += c;
}
for (; index < str_2.length(); ++index)
{
int temp_2 = (int)(str_2[index] - '0');
int temp = temp_2 + over_value;
value = temp % 10;
over_value = temp / 10;
char c = (char)(value + '0');
result += c;
}
if (over_value > 0)
{
char c = (char)(over_value + '0');
result += c;
}
reverse(result.begin(), result.end());
return result;
}
int main()
{
string a = "1";
string b = "1";
string c = addTwoString(a, b);
int index = 3;
while (c.length() < 1000)
{
a = b;
b = c;
c = addTwoString(a, b);
++ index;
}
cout << index << endl;
}
I just used a recursive function that adds arrays vertically to complete the problem. Basically zero run time, less than 50 lines of code. Enjoy:
#include <stdio.h>
int Calc_Fib (int numA[], int numB[], int temp[], int index) {
int i = 0;
//Check 1000th digit for non-zero value.
if (numB[999] != 0) return index;
//Add arrays A and B vertically.
for (i = 0; i < 1000; ++i) {
temp[i] += (numA[i] + numB[i]);
if (temp[i] > 9) {
temp[i + 1] = temp[i] / 10;
temp[i] %= 10;
}
numA[i] = numB[i];
numB[i] = temp[i];
temp[i] = 0;
}
Calc_Fib(numA, numB, temp, ++index);
}
int main() {
int numA[1000]; //Holds previous term.
int numB[1000]; //Holds current term.
int temp[1000]; //Holds temporary number for vertical addition.
int i = 0;
int indexVal = 2;
for (i = 0; i < 1000; ++i) {
numA[i] = 0;
numB[i] = 0;
temp[i] = 0;
}
//Initialize first two terms.
numA[0] = (numB[0] = 1);
indexVal = Calc_Fib(numA, numB, temp, indexVal);
printf("Tada: %d\n", indexVal);
return 0;
}