P
P
Pbalordorbaor2020-10-29 23:19:46
C++ / C#
Pbalordorbaor, 2020-10-29 23:19:46

What would be the best way to write the code?

#include <iostream>

int main() {
    int a = 4668;
    int b = 10415;
    int c = 0;
    int minValue = 0;
    for(int i=a; i<b; i++) {
        if(i%3==0 || i%11==0) {
            if(i%2!=0 && i%13!=0 && i%22!=0 && i%33!=0) {
                c++;
                if(c == 1) {
                    minValue = i;
                }
            }
        }
    }
    std::cout << c << minValue << "\n";
}

It seems to me that all these nested if smacks of shit, can someone give an example of a more beautiful code?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Daniil Naumovets, 2020-10-30
@Pbalordorbaor

1) It makes no sense to do nested conditional statements.
2) It makes no sense to check for non-multiplicity by 22, because we already check for non-multiplicity of 2.
3) In functions of type int, there must always be a return of a number of type int, return 0 is used at the entry point (main).

#include <iostream>
using namespace std;

int main() {
    int a = 4668;
    int b = 10415;
    int c = 0;
    int minValue = 0;
    for(int i=a; i<b; i++) {
        if(i%13!=0 && i%2!=0 && i % 33!=0 && (i%3==0 || i%11==0)) {
            c++;
            if(c == 1) {
                minValue = i;
            }
        }
    }
    cout << c << minValue << endl;

    return 0;
}

D
Denis Zagaevsky, 2020-10-30
@zagayevskiy

such nested ifs can be replaced by a single if with a conjunction of conditions.
c, c++ and checks can be replaced with a break at the end of the if body.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question