Skip to content

# How to Solve Simple Beads Count in C

## The challenge

Two red beads are placed between every two blue beads. There are N blue beads. After looking at the arrangement below work out the number of red beads.

@ @@ @ @@ @ @@ @ @@ @ @@ @

Implement `count_red_beads(n)` (`countRedBeads(n)`) so that it returns the number of red beads.
If there are less than 2 blue beads return 0.

## The solution in C

Option 1:

```.wp-block-code {
border: 0;
padding: 0;
}

.wp-block-code > div {
overflow: auto;
}

.shcb-language {
border: 0;
clip: rect(1px, 1px, 1px, 1px);
-webkit-clip-path: inset(50%);
clip-path: inset(50%);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
word-wrap: normal;
word-break: normal;
}

.hljs {
box-sizing: border-box;
}

.hljs.shcb-code-table {
display: table;
width: 100%;
}

.hljs.shcb-code-table > .shcb-loc {
color: inherit;
display: table-row;
width: 100%;
}

.hljs.shcb-code-table .shcb-loc > span {
display: table-cell;
}

.wp-block-code code.hljs:not(.shcb-wrap-lines) {
white-space: pre;
}

.wp-block-code code.hljs.shcb-wrap-lines {
white-space: pre-wrap;
}

.hljs.shcb-line-numbers {
border-spacing: 0;
counter-reset: line;
}

.hljs.shcb-line-numbers > .shcb-loc {
counter-increment: line;
}

.hljs.shcb-line-numbers .shcb-loc > span {
padding-left: 0.75em;
}

.hljs.shcb-line-numbers .shcb-loc::before {
border-right: 1px solid #ddd;
content: counter(line);
display: table-cell;
padding: 0 0.75em;
text-align: right;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
white-space: nowrap;
width: 1%;
}
```int countRedBeads(n) {
if(n<=1) return ;
return 2*(n-1);
}```Code language: C++ (cpp)```

Option 2:

``````int countRedBeads(n) {
if (n < 2) {
return ;
} else {
return n + (n-2);
}
}```Code language: C++ (cpp)```

Option 3:

``````int countRedBeads(n)
{
return n<2 ?  : 2*n-2;
}```Code language: C++ (cpp)```

## Test cases to validate our solution

``````#include <criterion/criterion.h>

int countRedBeads (int n);

Test(sample_tests, should_pass_all_the_tests_provided)
{
cr_assert_eq(countRedBeads(), );
cr_assert_eq(countRedBeads(1), );
cr_assert_eq(countRedBeads(3), 4);
cr_assert_eq(countRedBeads(5), 8);
}```Code language: C++ (cpp)```

See also  How to Check for All Inclusive in C
Tags:
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x