본문 바로가기
프로그래머스코딩테스트연습풀이/C언어

[프로그래머스/C언어] 등차수열의 특정한 항만 더하기

by 코코쵸마 2023. 8. 4.

문제

두 정수 a, d와 길이가 n인 boolean 배열 included가 주어집니다. 첫째항이 a, 공차가 d인 등차수열에서 included[i]가 i + 1항을 의미할 때, 이 등차수열의 1항부터 n항까지 included가 true인 항들만 더한 값을 return 하는 solution 함수를 작성해 주세요.

 

솔루션

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

// included_len은 배열 included의 길이입니다.
int solution(int a, int d, bool included[], size_t included_len) {
    int answer = 0;
    int i;
    int sum = 0;
    for(i = 1; i <= included_len; i++)
        if(included[i-1])
            sum += a + (i - 1) * d;
    answer = sum;
    return answer;
}

https://school.programmers.co.kr/learn/courses/30/lessons/181931

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr