Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

About improve code in this book #10

Open
chncys opened this issue Jul 20, 2023 · 0 comments
Open

About improve code in this book #10

chncys opened this issue Jul 20, 2023 · 0 comments

Comments

@chncys
Copy link

chncys commented Jul 20, 2023

in page 14, code of using flag as follows. the ans = 5913.

bool flag = true;
int ans = 0;
for (int i = 1; i <= 10 && flag; ++i)
{
int t = 1;
for (int j = 1; j <= i && flag ; ++j)
{
t *= j;
if (t > 1000) flag = false;
}
ans += t;
}

in page 14, code of using goto as follows. the ans = 873.

int ans = 0;
for (int i = 1; i <= 10; ++i)
{
int t = 1;
for (int j = 1; j <= i; ++j)
{
t *= j;
if (t > 1000) goto loop;
}
ans += t;
}
loop:;

this is because ans += t; excute more once in first code.
so we can move if statement to behiend the ans += t;
the new code as follwos, the ans = 5913.

int ans = 0;
for (int i = 1; i <= 10; ++i)
{
int t = 1;
for (int j = 1; j <= i; ++j)
{
t *= j;
}
ans += t;
if (t > 1000) goto loop;
}
loop:;

chncys
email: [email protected]
qq: [email protected]
WeChat ID: cys7749

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant