Ask Question
6 December, 23:40

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).

+3
Answers (1)
  1. 7 December, 02:18
    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?
Find 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 and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers