问题描述:

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…

网友答案:
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)
相关阅读:
Top