Recursive algorithm does not work

Asked

Viewed 212 times

2

I have to solve an exercise, and it says:

Do a procedure that receives an integer and positive n number. The procedure shall print all numbers in the range 0 to n which are divisible by 2 and 3 (simultaneously).

I’m starting at the moment, and I have very little baggage in data structure. I developed the code below, but does not return me the numbers that are divisible.

using System;

namespace revisao
{
class Program
    {               
        static void Imprimir(int[] vet, int indice)
        {               
            if (indice > 0 && indice < vet.Length)
            {
                if((vet[indice] % 2 == 0) && (vet[indice] % 3 == 0))
                {
                    Console.Write("{0,3}", vet[indice]);    
                    Imprimir(vet, indice + 1);
                }
                else
                {
                    Console.Write("Números não divisíveis por 2 e 3 simultaneamente!");
                }
            }
        }

        public static void Main(string[] args)
        {
            int i, tamanho;

            Console.Write("Digite o tamanho do vetor: ");
            tamanho = Convert.ToInt32(Console.ReadLine());

            int[] vetor = new int[tamanho];

            for(i = 0; i < vetor.Length; i++)
            {
                Console.Write("Digite o elemento {0}: ", i);
                vetor[i] = Convert.ToInt32(Console.ReadLine());
            }

            Imprimir(vetor, i);

            Console.ReadKey();
        }
    }
}

2 answers

1


I improved a few things to make the code more C-like. I also solved some other problems that the code had that are not in the statement, but if not treat it gives error. For lack of a specific definition when something is typed wrong I assumed what I wanted to solve.

I think the difficulty is the recursive function that the statement does not ask for and there is no need for use there. This is not a clearly recursive case, it is sequential, so a loop is more interesting.

If you are using an old version you have to declare the variable tamanho out of function TryParse() before using.

using static System.Console;

namespace revisao {
    public class Program {   
        public static void Main(string[] args) {
            Write("Digite o tamanho do vetor: ");
            if (int.TryParse(ReadLine(), out var tamanho)) {
                int[] vetor = new int[tamanho];
                for(int i = 0; i < vetor.Length; i++) {
                    Write($"Digite o elemento {i}: ");
                    vetor[i] = int.TryParse(ReadLine(), out var valor) ? valor : 0;
                }
                Imprimir(vetor);
            }
        }
        private static void Imprimir(int[] vetor) {
            WriteLine("Valores divisíveis por 2 e 3 simultaneamente");
            foreach (var item in vetor) if (item % 6 == 0) WriteLine($"{item}");
        }
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

1

Please print the numbers from 0 to n, n provided, which are divisible by 2 and 3 simultaneously. As @Maniero realized, it needs to be multiple of 6.

Since the question says nothing about storing in a vector, nor in later entries, there is only one reading for each instance of the problem. That is the point I was dissatisfied with his reply and also with the attempt of the AP response.

Since the initial number is 0, and 0 for being absorbent element in the ring of integers is multiple of all other numbers, just start from 0 and increment from 6 in 6 units until you reach n (I am assuming open interval in n). Based on Maniero’s code:

using static System.Console;

namespace revisao {
    public class Program {   
        public static void Main(string[] args) {
            Write("Digite n: ");
            if (int.TryParse(ReadLine(), out var n)) {
                WriteLine("Valores divisíveis por 2 e 3 simultaneamente");
                for (int i = 0; i < n; i += 6) {
                    WriteLine($"{i}");
                }
            }
        }
    }
}

Only multiples of 2 and 3 are printed simultaneously.

The recursive function for this would be kind of crude:

public static void imprimeRecursivo(int atual, int n) {
    if (atual < n) {
        WriteLine($"{atual}");
         imprimeRecursivo(atual + 6, n);
    }
}

The first call needs to pass as atual 0.

If you want to turn into a head recursion, you will only need one parameter:

public static void imprimeRecursivoCabeca(int i) {
    if (i >= 0) {
        imprimeRecursivoCabeca(i-1);
        if (i % 6 == 0) {
            WriteLine($"{i}");
        }
    }
}

If you want the interval opened at n, the first parameter is n-1. Note that it will converge to 0, where it will then begin to return recursions, printing in ascending order the multiples of 6 found.

Browser other questions tagged

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