Click here to Skip to main content
15,902,189 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
Given natural number n<10. Find all rational numbers in range [0,1] for which denominator doesn't exceed n.


Problem:
All rational numbers with numerator 1 like ½, 1/3, ¼ are missing

What I have tried:

#include <iostream>
using namespace std;

int main() {
    int n;
    cout<<"Enter n"<<endl;
    cin >> n;

    cout << "1/1" << endl;

    for (int denominator = 1; denominator <= n; denominator++) {
        for (int numerator = 1; numerator < denominator; numerator++) {
            if (denominator % numerator != 0) {
                cout << numerator << "/" << denominator << endl;
            }
        }
    }
    return 0;
}
Posted
Updated 24-Nov-21 17:00pm
Comments
Patrice T 18-Nov-21 5:00am    
Wgat is the question?
jasmeet singh 2021 24-Nov-21 18:24pm    
Question is not to print duplicates such 2/4, 6/8.
Print only reduced fractions
The original question is posted above.
jasmeet singh 2021 21-Nov-21 11:57am    
The program should nor print repeated values like 6/8 because its 2/3 which is already there. How to do that?
1/1
1/2
1/3
2/3
1/4
2/4
3/4
1/5
2/5
3/5
4/5
1/6
2/6
3/6
4/6
5/6
1/7
2/7
3/7
4/7
5/7
6/7
1/8
2/8
3/8
4/8
5/8
6/8
7/8

I guess you need
C++
if (denominator % numerator < n) {
but you really should visit some Learn C++ tutorial to understand the language and the developer tools instead of guessing around.
 
Share this answer
 
Comments
jasmeet singh 2021 18-Nov-21 6:15am    
Thanks that helps.
Could you help me to write the same code in Python?
#include <iostream>
using namespace std;

int main() {
int n;
cout<<"Enter n"<<endl;
cin="">> n;

cout << "1/1" << endl;

for (int denominator = 1; denominator <= n; denominator++) {
for (int numerator = 1; numerator < denominator; numerator++) {
if (denominator % numerator < n) {
cout << numerator << "/" << denominator << endl;
}
}
}
return 0;
}
You are almost there.
However, in order to remove duplicates the check you should perform is that GCD of numerator and denominator is 1, instead of (den % num == 0).
See std::gcd - cppreference.com[^].
 
Share this answer
 
v2
Quote:
C++
if (denominator % numerator != 0)
What precisely do you think that line is doing?

Modulo Operator (%) in C/C++ with Examples - GeeksforGeeks[^]

For example, 2 % 1 will not be 0, so your code will not output 1/2.
 
Share this answer
 
Quote:
Question is not to print duplicates such 2/4, 6/8.
Print only reduced fractions

Looks like you are looking for the farey sequence Farey sequence - Wikipedia[^]
I would switch to recursive code.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900