jeudi 2 février 2017

How to sort number that are in p/q formate using c++

How to Sort the given fraction in using c or c++.

Input- 0/1 ,1/5 , 1/6 , 1/4 , 1/3 , 1/2 , 2/5 , 3/6 , 2/3 , 3/5 , 3/4 , 4/5 ,5/6 , 1/1

Output-0/1 ,1/6 , 1/5 , 1/4 , 1/3 , 2/5 , 1/2 , 3/6 , 3/5 , 2/3 , 3/4 , 4/5, 5/6 , 1/1 .

I have written code in c++ but it not giving correct output

#include<iostream>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#include<set>
using namespace std;

long gcd(long a, long b);

void foo(double input)
{    

     double frac = input ;
    const long precision = 1000000000; // This is the accuracy.

    long gcd_ = gcd(round(frac * precision), precision);

    long denominator = precision/gcd_;
    long numerator = round(frac * precision) / gcd_;
    cout << numerator << "/" << denominator <<",";
}

long gcd(long a, long b){

if (a == 0)
        return b;
    else if (b == 0)
        return a;

    if (a < b)
        return gcd(a, b % a);
    else
        return gcd(b, a % b);
}


int main()
{

    double n;
    set<double>s;
    int c=0;
    cin>>n;
    for(int i=1;i<n;i++)
    {
        for(int j=n;j>0;j--)
        {
            if(i<j)
            {
            s.insert((double)i/j);
            }


        }
    }
    cout<<"0/1"<<",";
    while(!s.empty())
    {
        foo(*s.begin());
          s.erase(s.begin());
    }
    cout<<"1/1";
}

Aucun commentaire:

Enregistrer un commentaire