Codewars: Achieve mastery through coding challenge
Codewars is a coding practice site for all programmers where you can learn various programming languages. Join the community and improve your skills in many languages!
www.codewars.com
문제
Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0.
For example:
summation(2) -> 3
1 + 2
summation(8) -> 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8
코드
(defpackage #:challenge/solution
(:use #:cl)
(:export #:summation))
(in-package #:challenge/solution)
(defun summation (n)
(loop for i
below (+ n 1)
sum i))
설명
1부터 입력한 숫자까지 차례로 더해가는 문제다.
Common Lisp에서 for i below x 는 0부터 x-1까지 반복한다는 뜻이다. 여기서 sum은 i에 들어가는 항목들의 합이라고 보면 된다. 아래는 The Common Lisp Cookbook에서 가져온 예제다. 1)
(loop for i from 1 to 3 sum (* i i))
;; 14
위 코드에서 i는 1에서 3까지 입력받고, i의 제곱들의 합을 돌려준다.
'컴퓨터과학 > Algorithm' 카테고리의 다른 글
[SQL] [Codewars] 7Kyu - SQL with LOTR: Elven Wildcards (0) | 2021.10.21 |
---|---|
[SQL] [Codewars] 7Kyu - Countries Capitals for Trivia Night (SQL for Beginners #6) (0) | 2021.10.14 |
[Common Lisp] [구름LEVEL] 16진수 (0) | 2021.10.07 |