HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Project Euler #1 - Multiples of 3 and 5

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
andprojectmultipleseuler

Problem

If we list all the natural numbers
below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum
of these multiples is 23.


Find the sum of all the multiples of 3 or 5 below 1000.

Can someone give me suggestions on how to improve this solution? Also, please tell me whether or not my programming style is good.

#include

int main()
{
    int a,b,c,d,sum3,sum5,sum15,total_sum;
    b=999/3;
    c=999/5;
    d=999/15;
    sum3=b*(3+999)/2;
    sum5=c*(5+995)/2;
    sum15=d*(15+990)/2;
    total_sum=sum3+sum5-sum15;
    printf("%d",total_sum);
    return 0;
}

Solution

-
Functions in C with no parameters should have a void parameter:

int main(void)


-
Variables should be declared/initialized on separate lines:

int a;
int b;
int c;
int d;
int sum3;
int sum5;
int sum15;
int total_sum;


-
Try to avoid single-character variable names. They're very ambiguous and say nothing about the variable's purpose. The only valid exception to this is loop counter variables.

-
Statements/blocks of different purposes should be separated to increase readability. That would be the divisions, the sums, and the printf().

-
Your operands should be spread out to make the lines more readable:

sum3 = b * (3+999) / 2;


-
Initializations should be done as late as possible to help aid in maintenance:

sum3 = b * (3+999) / 2;


-
Remove int a since it's never used.

Code Snippets

int main(void)
int a;
int b;
int c;
int d;
int sum3;
int sum5;
int sum15;
int total_sum;
sum3 = b * (3+999) / 2;
sum3 = b * (3+999) / 2;

Context

StackExchange Code Review Q#28936, answer score: 4

Revisions (0)

No revisions yet.