我有一系列数字如下:
1,1,5,13,41,121,365,......
前两个值是:
N(1)= 1且N(2)= 1
从第3个值开始,N(i)= 2 * N(i-1)+ 3 * N(i-2)
我面临的问题是:如果我给出p的参数,它应该返回序列的最后一个值< p(使用fortran77)。
例如,如果p = 90,则应返回值41.
答案 0 :(得分:2)
a = 1
b = 1
while b < p:
c = 2 * b + 3 * a
a = b
b = c
return a
Fortran等价物是:
function fct(p) result(a)
integer, intent(in) :: p
integer :: a, b, c
a = 1
b = 1
do while (b < p)
c = 2 * b + 3 * a
a = b
b = c
enddo
end function
program test
integer :: fct
external fct
print *,fct(90)
end program
答案 1 :(得分:0)
假设您已经在变量lst
中设置了序列,并设置了p
,
max(filter(lambda x:x<=p, lst))
答案 2 :(得分:0)
def get_last_element(p):
n1 = 1
n2 = 1
while True:
if n2 > p:
return n1
n1, n2 = n2, 2*n2 + 3 * n1
print(get_last_element(90))
答案 3 :(得分:0)
我在Fortran 2003中编写了一段代码。我定义了一个类型,它具有序列的两个最后部分的内存。该过程是一个递归函数。该类型可以单独使用以获得序列的第n部分,或者有效地放置在循环中以查找连续的部分(不一定从1开始),因为它具有先前部分的存储器。 (编译器:gfortran 4.8)。
该类型在mymod.f90文件中定义为
module mymod
implicit none
type seq_t
integer :: saved_i = 0, saved_val_i = 0, saved_val_i_1 = 0
contains
procedure :: getpart => getpart_seq
end type
contains
recursive function getpart_seq(this,i) result(r)
class(seq_t) :: this
integer, intent(in) :: i
integer :: r,r_1,r_2
if (i.eq.1.or.i.eq.2) then
r = 1
elseif(i.eq.this%saved_i) then
r = this%saved_val_i
elseif(i.eq.this%saved_i-1) then
r = this%saved_val_i_1
else
r_1 = this%getpart(i-1)
r_2 = this%getpart(i-2)
r = 2*r_1 + 3*r_2
this%saved_val_i_1 = r_1
end if
this%saved_i = i
this%saved_val_i = r
end function getpart_seq
end module mymod
所请求案例的主要程序是
program main
use mymod
implicit none
type (seq_t) :: seq
integer :: i,p,tmp_new,tmp_old,ans
! Set the threshold here
p = 90
! loop over parts of the sequence
i = 0
do
i = i + 1
tmp_new = seq%getpart(i)
print*,tmp_new
if (tmp_new>p) then
ans = tmp_old
exit
end if
tmp_old = tmp_new
end do
print*,"The last part of sequence less then",p," is equal to",ans
end program
结果是
1
1
5
13
41
121
The last part of sequence less then 90 is equal to 41.