Write an ML function sue which given an integer n computes t

Write an ML function sue which, given an integer n computes the sum of the first n naturals. Namely, it computes: sigma_i = 0^ni fun sum n = ... Extent your suit function into a sumsq function. Given a natural n, sumsq computes the sum of the squares of the first n naturals: sigma_i = 0^i^2 fun sumsq n = ... Write an ML function sumOdd which, given a natural n computes the sum of the first n odd naturals. For instance, sumOdd 4 1 + 3 + 5 + 7 (i.e., we have four terms). fun sumOdd n = ... Write an ML function fib that computes, from an integer input n, the n^th Fibonacci number (as always, fib(i) = fib(i - 1) -f fib(i - 2),fib(0) = 0,fib(1) = 1). fun fib n = ... Write an ML function fibFast that computes, in linear time, from an integer input n, the n^th Fibonacci\'s number. fun fibFast n = ...

Solution

1.

Your sum function would be:

Or making a tail-recursive version:

Or simply using folding:

2.

3.

my_sum = 0;
for ii = 1:100
   if ii%2<>0
       my_sum = my_sum + ii;
end

4.

N=input(\'Pick a number\ \');
fib=zeros(1:N);
fib(1)=1;
fib(2)=1;
k=3;
while k <= N
    fib(k)=fib(k-2)+fib(k-1);
    k=k+1;
end


fprintf(\'The Fibonacci sequence to %d terms is %g \ \',N,fib);

 Write an ML function sue which, given an integer n computes the sum of the first n naturals. Namely, it computes: sigma_i = 0^ni fun sum n = ... Extent your su

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site