Menu
Coddy logo textTech

A solution with no loops

Lesson 3 of 20 in Coddy's Mathematical Riddles course.

Previous challenge is easily solved using loops. However, if N is big - for example N=10**9 - runtime might be long, very long.

If you solved previous challenge without loops - it is great, and you are very good, both in programming and in mathematics. If you didn't, this lesson is for you.

Another way is calculating directly the sum of each arithmetic.

If you know the first term, a1, last term, an, and the number of terms, n, the sum is:

S = n * (a1+an)//2

challenge icon

Challenge

Easy

Use the sum formula to calculate the solution for the challenge.

Write a function calc which takes integer N as input and returns the sum of the multiples of 3 or 5 below N .

For example for N=10 the function will return 23

Tip - Separate your code into smaller functions.

Try it yourself

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "solution.h"

int main() {
    int n;
    if (scanf("%d", &n) != 1) n = 0;
    int r = calc(n);
    printf("%d\n", r);
    return 0;
}

All lessons in Mathematical Riddles

2Multiples of 3 or 5

A problemA solution with no loops

5Diophantine Equation

IntroductionA problem