기초수학(계차수열, 피보나치 수열, 팩토리얼)

Lee JunBok·2023년 4월 19일

기초수학

목록 보기
3/5
post-thumbnail

계차수열

어떤 수열의 인접하는 두항의 차로 이루어진 또 다른 수열

# an = {3, 7, 13, 21, 31, 43, 57}
# b       4  6   8  10   12  16

inputAN1 = int(input('a1 입력: '))
inputAN = int(input('an 입력: '))

inputBN1 = int(input('b1 입력: '))
inputBD = int(input('bn 공차 입력: '))

valueAN = 0
valueBN = 0

n = 1
while n <= inputAN:

    if n == 1:
        valueAN = inputAN1
        valueBN = inputBN1
        print('an의 {}번째 항의 값: {}'.format(n, valueAN))
        print('bn의 {}번째 항의 값: {}'.format(n, valueBN))
        n += 1
        continue

    valueAN = valueAN + valueBN
    valueBN = valueBN + inputBD

    print('an의 {}번째 항의 값: {}'.format(n, valueAN))
    print('bn의 {}번째 항의 값: {}'.format(n, valueBN))
    n += 1

print('an의 {}번째 항의 값: {}'.format(inputAN, valueAN))
print('bn의 {}번째 항의 값: {}'.format(inputAN, valueBN))    

피보나치 수열

세 번째 항은 두 번째 항과 첫 번째 항을 더한 합이다.

inputN = int(input('n입력 : '))

valueN = 0
sumN = 0

valuePreN2 = 0
valuePreN1 = 0

n = 1
while n <= inputN:
    if n == 1 or n == 2:
        valueN = 1
        valuePreN2 = valueN
        valuePreN1 = valueN

        sumN += valueN
        n += 1

    else:
        valueN = valuePreN2 + valuePreN1
        valuePreN2 = valuePreN1
        valuePreN1 = valueN
        sumN += valueN
        n += 1

print('{}번째 항의 값 : {}'.format(inputN, valueN))
print('{}번째 항까지의 값 : {}'.format(inputN, sumN))

팩토리얼

1부터 양의 정수 n까지의 정수를 모두 곱한 것

inputN = int(input('n 입력 : '))

result = 1

for n in range(1, (inputN + 1)):
    result *= n

print('{}팩토리얼 : {}'.format(inputN, result))
# 재귀함수
inputN = int(input('n 입력 : '))

def factorialFun(n):
    if n == 1: return 1

    return n * factorialFun(n - 1)

print('{}팩토리얼 : {}'.format(inputN, factorialFun(inputN)))
# 모듈
import math

print('{}팩토리얼 : {}'.format(inputN, math.factorial(inputN)))

이글은 제로베이스 데이터 취업스쿨의 강의자료 일부를 발췌하여 작성되었습니다.

profile
Learning Data Analyst

0개의 댓글