tiberiu714
tiberiu714

Reputation: 11

The subroutine returns the sum of the positive divisors of n that are not prime

The sum subprogram has a single parameter, n, through which it receives a natural number (n [1,106]). The subroutine returns the sum of the positive divisors of n that are not prime. Write the complete definition of the subroutine. Example: for n = 12 the subroutine returns 23 (23 = 1 + 4 + 6 + 12).

This is what i've tried, but no results..

int suma(int n)
{
    int d,s=0,prim;
    prim=1;
    if(n<2)
    {
        prim=0;
        s=n;
    }
    for(d=2; d*d<=n; d++)
    {
        if(n%d==0)
            prim=0;
        if(prim==0)
            s+=d;
    }
    return s;
}

Upvotes: 1

Views: 101

Answers (1)

Thomas Sablik
Thomas Sablik

Reputation: 16454

I rewrote some parts of your code to make it a bit cleaner and highlighted the missing function in your current code.

bool isPrime(int d) {
    /* TODO */
}

int suma(int n)
{
    int s = 1; // you can always start with 1
    // n if n is not prime
    if (!isPrime(n)) {
        s += n;
    }
    // bool prim=true; // you don't need it
    /* if(n<2)
    {
        // prim=false;
        s=n;
    }*/ // this block doesn't make sense for me
    for(int d = 2; 2 * d <= n; ++d) // the loop has to iterate from 2 to n/2
    {
        if(n % d == 0) { // d is a positive divisor of n
            if(!isPrime(d)) { // check if d is prime
                s += d;
            }
        }
    }
    return s;
}

Upvotes: 1

Related Questions