
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Simplified Fractions in C++
Suppose we have an integer n, we have to find a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator <= n. Here the fractions can be in any order.
So, if the input is like n = 4, then the output will be ["1/2","1/3","1/4","2/3","3/4"] as "2/4" is not a simplified fraction because it can be simplified to "1/2".
To solve this, we will follow these steps −
Define an array ret
for initialize i := 2, when i <= n, update (increase i by 1), do −
for initialize j := 1, when j < i, update (increase j by 1), do −
c := gcd of i and j
a := j / c
b := i / c
insert (a as string concatenate "/" concatenate b as string) at the end of ret
return an array of all unique elements present in ret
Example
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; void print_vector(vector<string> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: vector<string> simplifiedFractions(int n) { vector<string> ret; for (int i = 2; i <= n; i++) { for (int j = 1; j < i; j++) { int c = __gcd(i, j); int a = j / c; int b = i / c; ret.push_back(to_string(a) + "/" + to_string(b)); } } set<string> s(ret.begin(), ret.end()); return vector<string>(s.begin(), s.end()); } }; main(){ Solution ob; print_vector(ob.simplifiedFractions(4)); }
Input
4
Output
[1/2, 1/3, 1/4, 2/3, 3/4, ]
- Related Articles
- Simplified Equivalent Circuit of Transformer
- What is the Simplified Data Encryption Standard?
- Unique Fractions in C++
- Write the fractions. Are all these fractions equivalent?"
- How to Convert Traditional Chinese to Simplified Chinese or Vice Versa in Excel?
- How do we convert improper fractions into mixed fractions?
- What are mixed fractions and how do you convert mixed fractions into improper fractions and vice versa?
- Representation of fractions
- What are Fractions?
- Fractions with the same denominator are called unlike fractions. True or False?
- Write the fractions and pair up the equivalent fractions from each row."
- Python Rational numbers (fractions)
- What are improper fractions?
- What are decimal fractions?
- How to multiply Fractions?
