6.1 Calculate multiples of 3

In this chapter, I will show you several examples on how to use the knowledge we have learnt before. These examples are of or close to real-world scenarios. If you haven’t done any programming before, those examples will help you to gain a good understanding on how programmers think and talk to computers.

Before look at the code, please try to write the code yourself after reading the problem. And test the code see whether it works. Then you can compare with my code.

The problem

If you have finished all the previous exercises, you might have already resolved this issue by yourself in last chapter. This issue is about calculating the multiples of 3 under 100, which is 3 + 6 + 9 + … + 99. While this issue is not hard, we will learn some general programming thinking by resolving it.

The code

Integer sum = 0;
for(Integer i = 3; i < 100; i += 3)
{
    sum += i;
}
System.debug('The sum is: ' + sum);

Your result should also be 1683.

Analysis

First thing we need to notice here is the afterthought of for loop part doesn’t have to be i++. It actually can be any statement. Here we have used i += 3.

So the problem is resolved. And it is a good resolution. But think about it. Is it the best solution yet?

Optimized Solution

Remember we have the below equation to calculate sum of arithmetic series:

sum-of-sequence

Hope this is not too much math here. Based on this equation, we can optimize our previous code:

Integer sum = (3 + 99) * 33 / 2;
System.debug('Sum is: ' + sum);

The result should be exactly the same.

A bit explanation

As this is the programming guide for beginners, it is not an algorithm book so I will not show you any most optimized solutions in the future. And I still recommend you to use more loops and conditional statements in your code to practice more. However, the reason I gave you the above optimized code is I want you to remember a very important concept in programming:

Although computer is good at doing repetitive tasks, it is always a good practice to reduce its workload to the minimum by writing more efficient code. 

Don’t need to overthink it for now. But when you program for real life projects, keep that concept in mind.

Next Post

6.2 Calculate multiples of 3 and 5

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

Your email address will not be published / Required fields are marked *