There is a program code that finds the sum of the divisors of the number. True, he is not mine and written personally for me is not clear. I tried to write the code (commented out), but nothing happened. Calculates only for odd numbers and that is not always correct. Tell me where I was wrong.

#include <iostream> using namespace std; //int sd(int n, int d=1) //{ // if (d <= n) // { // if(n % d == 0) // return d + sd(n, d + 1); // else // return sd(n, d + 1); // } //} int sd(int n, int d=1) { return d <= n ? (n % d == 0? d + sd(n, d + 1) : sd(n, d + 1)) : 0; } int main() { setlocale(LC_ALL, "rus"); int n; cout<<"Дано натуральное число найти сумму его делителей через рекурсию \n"<<endl; cout << "Введите натуральлное число, n = "; cin >> n; cout <<"Сумма делителей натурального числа = "<<sd(n)<<endl; system ("pause"); return 0; } 

    2 answers 2

     int sd(int n, int d=1) { return d <= n ? (n % d == 0? d + sd(n, d + 1) : sd(n, d + 1)) : 0; } 

    ==>

     int sd(int n, int d=1) { if(d <= n) //Если делитель меньше нужного числа, то идем дальше { if( n % d == 0) //если число n делится на d без остатка { return d + sd(n, d+1); //возвращаем сумму этого делителя + все суммы остальных делителей, которые делятся без остатка. } else { return sd(n, d+1); //возвращаем суммы остальных делителей, которые делятся без остатка } } else { return 0; //на этой итерации нет делителей для числа } } 
    • ps. I wonder if the topic starters will not pretend to be girls, then no one will answer them at all? - Deadkenny
    • @Deadkenny: Yeah. If only the photo was applied to the profile. - VladD
    • Thank you very much. Now I see my mistake - mashanka

    Oh, and good code. Written by a man who has heard about recursion (though not about tail).

    See it. The sd function is in two copies. They are equivalent, just the first option is easier painted. Let's take it and consider.

    So, how do we determine the amount of dividers? We define the function sd(n, d) : the sum of the divisors of the number n that are greater than or equal to d . Why is that? Because this function is easy to define recursively, and it gives us the desired result, if we set d = 1 .

    The recurrence ratio is:

    1. If n is divisible by d , then d is one of the divisors, and sd(n, d) is d plus the other divisors (that is, for large d ). So, for this case, sd(n, d) = d + sd(n, d + 1) .
    2. If not divided, then obviously sd(n, d) = sd(n, d + 1)
    3. If d > n , sd(n, d) = 0 , and then you can not count.

    Accordingly, the code:

     int sd(int n, int d=1) { if (d <= n) // случай 3? { // нет. тогда может случай 1? if(n % d == 0) return d + sd(n, d + 1); // да! else return sd(n, d + 1); // нет, случай 2. } // тут потеряно else return 0; для полного разбора случая 3 // в незакомментированной функции этот случай есть } 

    With you something tasty for someone who wrote the code.


    Yes, and the code is correct.