Ask Question
28 July, 14:55

Write a function prodby2 that will receive a value of a positive integer n and will calculate and return the product of the odd integers from 1 to n (or from 1 to n-1 if n is even). Use a for loop. Then, write a new function prodby2vectorized that performs the same task using vectorized code (without using for loops).

+2
Answers (1)
  1. 28 July, 18:45
    0
    long long int prodby2 (int n) / /function using for loop ...

    {

    long long int prod=1;

    for (int i=1; i<=n; i+=2)

    {

    prod*=i;

    }

    return prod;

    }

    long long int prodby2vectorized (int n) / /function without the use of for loop ...

    {

    if (n<=1)

    return 1;

    if (n%2 = = 0)

    n--;

    else

    {

    return n*prodby2vectorized (n-2); / /recursive call ...

    }

    }

    Explanation:

    Two functions are written above prodby2 uses for loop while prodby2vectorized uses recursion. Both the functions are of long long int type because product can be very large. In the for loop it starts from 1 and i is increased by 2 so that i is always an odd number. Storing the product in prod variable.

    In second function I have used recursion if n is less than or equal to 1' the function will return 1. If n is even it will decrease n else recursively calculate the result.
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “Write a function prodby2 that will receive a value of a positive integer n and will calculate and return the product of the odd integers ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers