I am stuck with a unique problem.
We have to find the sum of digits in 2^1000.
The code below is giving correct output.
However when I change the value of digit from 1000 to anything <=604,
It shows wrong output.
The number of digit in 2^1000 is 302 and sum of digit is 1366.
Also note that 604=2*302,
so is there any relation??
Please solve my problem..

#include<iostream>
using namespace std;
#define digit 1000
int main()
{
	int num[digit]={0},i,j=0,ctr,carry,length=1; 
	
	num[digit-1]=1;
	while (j<1000)
		{ carry=0;
			
		   for (i=0;i<length;++i)
			{ ctr=num[digit-1-i]*2;
			   num[digit-1-i]=(carry+ctr)%10;
			   carry=(carry+ctr)/10;
			    if (i==length-1&&carry!=0)
				{ ++length;
				   num[length]=carry;
				}
			}
		  ++j;
		}
		
	int sum=0;
	for (i=0;i<length;++i)
	sum+=num[digit-1-i];
	cout<<sum;
	
	return 0;
}

An ordinar problem with wrong index expression ;)
Corrected code (test it! ) :

// preferred way to define constants in C++
const size_t digits = 1000;
/// max power ~3000
unsigned Dig2N(unsigned power = 1000)
{
    unsigned num[digits] = {0};
    unsigned ctr, carry; 
    unsigned length = 1;
	
    num[digits-1] = 1;
    for (unsigned j = 0; j < power; j++)
    { 
        carry=0;
        for (unsigned i=0; i < length; ++i)
        { 
            ctr = num[digits-1-i]*2;
            num[digits-1-i] = (carry+ctr)%10;
            carry = (carry+ctr)/10;
            /* remove it from the loop body
            if (i == length-1 && carry != 0)
            {
                ++length;
                num[length] = carry; // wrong index!!!
            }
            */
        }
        if (carry != 0)
        {
            ++length;
            num[digits-length] = carry; // That's it!
        }
    }

    unsigned sum=0;
    for (unsigned i=0; i < length; ++i)
        sum += num[digits-1-i];
    cout << "2^" << power << " sum " << sum 
        << " nod " << length << endl;
    return length;
}

It was a wrong place for carried digits...

By the way, no need to start from the right side of the num array. Better form digits left to right (in reverse order) - use simple index expressions...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.