Home > Mobile >  How to get arbitrary return values in c
How to get arbitrary return values in c

Time:12-22

I am trying to write divisor function, Which gives all divisor of given number. But in that I do not want any array rather I want to return every divisors one by one. Is it possible?

This is code :

auto allDivisor(int num){
    for (int i=1; i<=num; i  ){
        if(num % i == 0){
            return i;
        }
    }

But I got only first iterations result: Enter integer number : 10 All divisior of 10 : 1

CodePudding user response:

#include <iostream>

void allDivisor(int num, void (*callback)(int)) {
    for (int i = 1; i <= num; i  ) {
        if (num % i == 0) {
            callback(i);
        }
    }
}

int main() {
    int num = 10;
    std::cout << "All divisors of " << num << ": ";
    allDivisor(num, [](int divisor) {
        std::cout << divisor << " ";
    });
    std::cout << std::endl;
    return 0;
}

The callback function is passed to the allDivisor function as an argument, and it is called once for each divisor of the input number.

CodePudding user response:

the usual way is to call your function multiple times and each time it will return different divisor until the end is marked by some special return value like 0 ... the iteration can be done either by passing i as function parameter or have it as global or static variable but that would make your function thread unsafe prohibiting to use it in parallel (even in serial overlapped with other division) ... It would look like this:

int allDivisor(int num)
    {
    static int i=0;
    for (i  ;i<=num;i  )
    if ((num%i)==0) return i;
    if (i>num){ i=0; return 0; }
    }

and usage:

int d,X;
for (X=32;;)
    {
    d=allDivisor(X);
    if (!d) break;
    cout << d;
    }
for (X=125;;)
    {
    d=allDivisor(X);
    if (!d) break;
    cout << d;
    }

outputting this:

1
2
4
8
16
32
1
5
25
125

however be sure you always call the allDivisor until it returns 0 otherwise its next usage would be messedup (skipped first divisors until last i state) ... that could be repaired too for example like this (at cost of another static variable):

int allDivisor(int num)
    {
    static int i=0,n=0;
    if (n!=num){ n=num; i=0; }
    for (i  ;i<=num;i  )
    if ((num%i)==0) return i;
    if (i>num){ i=0; return 0; }
    }
  • Related