C++ code to find name with O's on Fibonacci positions


Suppose we have a number n. Amal wants to give a name to his pet. He will follow an algorithm. The name will be n characters long. The name will contain uppercase and lowercase letters 'O's and 'o's. The algorithm suggests the i-th letter of the name should be 'O' (uppercase) if i is a member of Fibonacci sequence, and 'o' (lowercase) otherwise. The letters in the name are numbered from 1 to n.

So, if the input is like n = 10, then the output will be "OOOoOooOoo", because first fibonacci numbers are 1, 2, 3, 5 and so on.

Steps

To solve this, we will follow these steps −

s := a string of size n and filled with 'o's
for initializing i and j from 1, when i <= n, increase i by j and set
j := i-j after each iteration, do
   s[i-1] := 'O'
return s.

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
string solve(int n){
   string s(n, 'o');
   for (int i = 1, j = 1; i <= n; i += j, j = i - j)
      s[i - 1] = 'O';
   return s;
}
int main(){
   int n = 10;
   cout << solve(n) << endl;
}

Input

10

Output

OOOoOooOoo

Updated on: 15-Mar-2022

71 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements