scheme - Lisp 程序(使用 Scheme 48 1.9 解释器)找出级数 1^3 + 2^3 + … 的总和。 + n^3

标签 scheme lisp

在截止日期午夜之前,将您的作品作为单个纯文本文件上交,其中包含定义所有必要功能的 SCHEME 代码。

LISP编程

  1. 编写一个 Lisp 函数 sumcubes,它接受一个数字 n 并返回总和 1*1*1 + 2*2*2 + ... + nnn。例如:

(求和立方体 0)

0

(总和立方体 4)100

(因为 13 + 23 + 33 + 43 = 1 + 8 + 27 + 64 = 100)

我已经看到如何在 C 中执行此操作,但在 LISP 中对其进行格式化时遇到了问题。

在此先感谢您的帮助(我对 LISP 几乎一无所知,我基本上有一个星期的时间来学习它)。

这是我看到的 C 代码中的内容 ( http://www.cquestions.com/2011/07/write-c-program-to-find-out-sum-of_19.html ):

Sum of 1^2 + 2^2 + …. + n^2 series in c programming language

#include<stdio.h>

int main(){

int n,i;
int sum=0;

printf("Enter the n i.e. max values of series: ");
scanf("%d",&n);

sum = (n * (n + 1) * (2 * n + 1 )) / 6; //I believe this is the crucial line I need.

printf("Sum of the series : ");

for(i =1;i<=n;i++){
     if (i != n)
         printf("%d^2 + ",i);
     else
         printf("%d^2 = %d ",i,sum);
}

return 0;
}

Sample output:

Enter the n i.e. max values of series: 5 Sum of the series: 1^2 + 2^2 + 3^2 + 4^2 + 5^2 = 55

Mathematical Formula:

Sum of the series 12 + 22 + 32 + … + n2 = n (n+1) (2n+1)/6

最佳答案

我自己得到了这个问题的答案。

> (define (sumcubes n) (expt (/ (* (+ 1 n) n) 2) 2))
; no values returned
> (sumcubes 3)
36
> (sumcubes 4)
100

关于scheme - Lisp 程序(使用 Scheme 48 1.9 解释器)找出级数 1^3 + 2^3 + … 的总和。 + n^3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34971304/

相关文章:

影响其他功能的 LISP 功能

clojure - 来自 SICP 的 Clojure 中的 count-leaves

方案环境模型收敛问题

testing - 方案平方和检验

scheme - Racket\Scheme 中的返回类型

lisp - "Don' t 知道如何从 : Symbol"error in Clojure 创建 ISeq

macros - 如何在 lisp 中用 if 形式定义递归 cond 宏?

scheme - 可以简化此功能(制作更多 "fast")吗?

scheme - 将数据写入方案中不存在的文件(通过程序创建后)

lisp - 抑制编译器错误