-1

I was just solving some problems at Euler when I came across a simple problem, no. 16, and I wrote a simple program.

#include<iostream>
#include<math.h>
using namespace std;

int main()
{
    unsigned long long num = pow(2,15);
    int sum=0;
    int rem,k=10;
    while(!num/10<10)
    {
        rem = num%10;
        sum+=rem;
        num=num/10;
    }
    sum+=num;
    cout<<"the sum of digits is "<<sum;
    return 0;
}

I don’t know why but this code is taking a lot more time than expected. How to optimize it? Many of my programs take a lot more time to complete the execution than expected…

Deanie
  • 2,316
  • 2
  • 19
  • 35

1 Answers1

7
while(!num/10<10)

is your problem.

You are dividing !num by 10;

The test should also be < 1

try

while(!(num/10<1))

or

while(num/10 > 0)
parkydr
  • 7,596
  • 3
  • 32
  • 42
  • I've made the changes and it worked good for 2 to the power 15 but its giving me incorrect results for 2 to the power 1000 Why? and thanx for the help – user3141305 Jan 26 '14 at 09:31
  • 2
    Couldn't we further assume that `num / 10 > 0` is equivalent to `num >= 10` which would be a tad bit faster? – Alexis Wilke Jan 26 '14 at 09:33
  • 1
    @user3141305 an unsigned long long is not long enough to hold the 1001 bits required. You should get an overflow warning from the compiler – parkydr Jan 26 '14 at 09:36
  • I had this problem before also whats the maximum type I could use in C++ – user3141305 Jan 26 '14 at 09:40
  • @AlexisWilke You're probably right and it would be a clearer solution too. – parkydr Jan 26 '14 at 09:41
  • @user3141305, you may want to see my answer here: http://stackoverflow.com/questions/21294581/calculate-floorpow2-n-10-mod-10-sum-of-digits-of-pow2-n/21298765#21298765 – Alexis Wilke Jan 26 '14 at 10:19