Print ranges of numbers with final 5

Asked

Viewed 623 times

-3

I’m trying to print the numbers from 0 to 200 that have only the number 5 as the last digit.

package Exercícios;

public class NumerosQueComeçamComAlgarimo5 {

    public static void main (String [] args) {

        for (int i = 0; i <= 200; i++) {
            System.out.println(i);
        }
    }
}
  • 9

    It would not be enough to start your counter with 5 and increase by 10? int i = 5; i <= 200; i += 10

  • 1

    A clear case of "first solve the problem, then write the code". How do you intend to check if the last digit is 5?

  • 1

    @Andersoncarloswoss I wanted to understand the "just", because in "they have only the number 5 as the last digit" suggests that it may have more than one last digit?

4 answers

19


It’s extremely simple and efficient because language has everything it needs to do this mathematically. It’s not a matter of programming, but solving a mathematical problem.

If you want to always show numbers with ending 5 you agree that you should start with 5?. And if you want to keep the distance between them always equal and keep the end 5 then we have a dozen difference, so we should increase the number by 10 by 10, then that’s it:

public class NumerosQueComeçamComAlgarimo5 {
    public static void main(String [] args) {
        for (int i = 5; i <= 200; i+= 10) System.out.println(i);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Please do not use any solution that is not pure mathematics, and simple, it makes no sense to do otherwise more complicated.

I kept the class title, but it seems wrong, or the problem statement is wrong. If the problem is what the title says, then the algorithm is a little more complex, but you can do it mathematically yet.

For some reason the question attracted diversity of solutions. This is usually good, except when each one is more convoluted than another. There was a blackout who worked with strings that it was very complicated, others exist with a complicated logic that added nothing, only worsened. There is an answer that gives an advantage that the question does not ask, but could make sense to other people. It may be that the person does not have the fixed parameters. The problem with the answer is that it has become too complicated and incredibly abstract of least. Clearly the answer tried to abstract certain parts, but failed to abstract what was most important. The answer would be good if it did:

public class NumerosQueComeçamComAlgarimo5 {
    public static void main(String [] args) {
        IncrementInterval(5, 200);
    }
    public static void IncrementInterval(int inicio, int limite) {
        for (int i = inicio; i <= limite; i+= 10) System.out.println(i);
    }
}

If you want you can do a validation and ensure that the limit is greater than the range, or check that the end is between 0 and 9.

It took only setting parameters at the beginning and end instead of creating one if meaningless and inefficient and create functions to hide something without any gain. OOP is destroying people’s heads.

I’m going to take this opportunity to let off steam about the state of our industry. People have lost track of the simple. Now everything has to be complicated to be "right". Have to do TDD, DDD, xDD, microservices, have to put in the cloud, on container, must have a build complex, having N layers, even the use of OOP is absurdly overvalued and abused. And abstraction also ends up creating excessive complexity, although often the lack of it is the real problem. It’s so hard to do a simple function and use a very simple loop?

3

Here’s a solution in case you want to check if any number ends at 5:

// só como explicação/demonstração, num caso real 
// se usa essa expressão diretamente
int digitoFinal(int numero) {
    return Math.abs(numero) % 10;
}

// vide comentário anterior
boolean terminaEmCinco(int numero) {
    return digitoFinal(numero) == 5;
}

// aqui num laço, novamente só como demonstrração
// ver resposta do Maniero 
for (var i = 0; i < 200; i++) {
    if (terminaEmCinco(i)) {  // ou if ((i % 10) == 5) {
        System.out.println(i);
    }
}

This solution is only to demonstrate a possibility in case you don’t have one loop, but, for example, a value returned from any function. Basically uses the fact that module 10 (% 10) applied to a number results in the last digit of that number.

Maniero’s answer is the most appropriate and efficient in the case of having fixed values (as required in the question).

  • 2

    I can’t believe what happened in that question has become a competition for the most far-fetched answer. I’m sorry for the outburst, but it’s unbelievable the state things have come to. No one else wants a simple solution. https://i.stack.Imgur.com/jgk8Q.png

  • 3

    I guess it didn’t stick Nterprise enough, needed to be terminaEmValor(int numeroA, int numeroB) { digitoFinal(numeroA) == numeroB :)

  • 2

    @Bacco but I think I needed to create a class and use the shared state among the methods, then it gets more fashionable.

  • 2

    I didn’t want to be too picky, so I didn’t even suggest doing a test class and a TDD.

  • 2

    The only intelligent solution that is different so far was given in chat by Anderson Carlos Woss: System.out.println("5, 15, 25, 35, 45, 55, 65, 75, 85, 95, 105, 115, 125, 135, 145, 155, 165, 175, 185, 195");, but of course she is slutty because it can’t be variable and probably goes against the exercise that is to make a loop, but it would be the simplest, though more verbose.

  • 2

    @Bacco DDD too, some DP

  • The solution was already presented at the beginning of the topic changing the counter, I know it was a simple question, but it is still a question. I am a beginner in the field of programming and I thank the members of the community for their collaboration, because they have a vast knowledge. But it is unnecessary to argue for a doubt already solved.

Show 2 more comments

-2

From what I understand you want to print the numbers that have their last digit finished in 5 (this is what it says in your question), ie : 5, 15, 25, 35 etc. Another way to solve this, besides the ones that colleagues mentioned above, would be to check if the number is even, Because if you jump from 5 to 5, it will be 5(odd), 10(even), 15(odd), 20(even)... so every time you have an odd number it will be finished in 5, in the code it would look like this:

public class numerosTerminadosEmCinco {

    public static void main(String[] args) {
        for (int i = 5; i <= 200; i += 10) {
            if (i % 2 != 0) {
                System.out.println(i);
            }
        }

    }

}
  • 2

    Why do this? What benefit is there in making a if unnecessary? If taking it out gives exactly the same result.

  • 3

    If you start at 5 and increase to 10, you never will have an even value - indeed, there is no way a number finished in 5 be even, then your condition will always be true. To prove this, just make 5 + 10k, being k integer, which can be rewritten as 5(2k+1); for this value to be multiple of 2 the factor (2k+1) needs to be even. There is no value of k integer that makes this value even.

-2

Maniero’s answer is perfect.

I would just like to add an option if you don’t want to change your loop, that is, iterating all the numbers from 0 to 200.

One way to determine if the last number is equal to 5, would be using the rest operator "%".

First: every number that is divisible by five ends in 5 or 0. Ex: 0, 5, 10, 15, 20, 25, etc. So if you use the rest operator splitting by five, you will only return the numbers that end in five and zero.

Second: to determine whether the number ends in 5 or 0, use the rest operator dividing by 2. In this case, only return remainder if the number ends in 5.

Ex:

public static void main(String [] args) {
    for (int i = 0; i <= 200; i++) {
        if((i % 5) == 0) {
            if((i % 2) != 0) {
                System.out.println(i);
            }
        }
    }
}
  • 3

    I find this so unnecessary. I don’t know why people are taking a simple solution and creating an inefficient solution that doesn’t help at all. Giving creative solutions has no value if they are worse than the one already offered. There are cases where the solution may be an alternative, but just because it is different and works doesn’t mean it is a good solution. Create 4 lines of code, 2 branchs that increases cyclomatic complexity and new execution instructions that are very expensive is not a good thing, only worsens readability for zero gain.

  • you don’t need 2 if you just need to put in the same line if((i % 5) == 0 && (i % 2) != 0)

  • It all starts with raising the bar. I already had to respond to an exercise where the loop was given and could not be changed, only code could be added to the body of the loop, so I offered this solution. If not changing the loop is a requirement of the exercise, the proposed solution does not resolve.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.