/* Test NaN-resulting library calls. */ int test_errs(void) { int errs = 0; /* * Attempt to prevent constant folding and optimization of library * function bodies (when statically linked). */ volatile double x; volatile double y; printf("Checking well-defined library errors\n"); x = -3.0; y = 4.4; errs += CHECK_NAN(pow(x, y)); errs += CHECK_NAN(log(x)); x = -0.001; errs += CHECK_NAN(sqrt(x)); x = 1.0001; errs += CHECK_NAN(asin(x)); x = INFINITY; errs += CHECK_NAN(sin(x)); errs += CHECK_NAN(cos(x)); x = 0.999; errs += CHECK_NAN(acosh(x)); x = 3.3; y = 0.0; errs += CHECK_NAN(remainder(x, y)); y = INFINITY; errs += CHECK_NAN(remainder(y, x)); return errs; }
void test_remainder() { static_assert((std::is_same<decltype(remainder((double)0, (double)0)), double>::value), ""); static_assert((std::is_same<decltype(remainderf(0,0)), float>::value), ""); static_assert((std::is_same<decltype(remainderl(0,0)), long double>::value), ""); static_assert((std::is_same<decltype(remainder((int)0, (int)0)), double>::value), ""); assert(remainder(0.5,1) == 0.5); }
void test_fp_remainder( void ) { #if __STDC_VERSION__ >= 199901L printf( "Testing C99 remainder function...\n" ); VERIFY( CompDbl( remainder( 2.01, 1.0 ), 0.01 ) ); VERIFY( CompDbl( remainder( 4.99, 2.0 ), 0.99 ) ); #endif }
void RS_Grid::createIsometricGrid(LC_Rect const& rect, RS_Vector const& gridWidth) { double const left=rect.minP().x; double const right=rect.maxP().x; //top/bottom reversed double const top=rect.maxP().y; double const bottom=rect.minP().y; int numberY = (RS_Math::round((top-bottom) / gridWidth.y) + 1); double dx=sqrt(3.)*gridWidth.y; cellV.set(fabs(dx),fabs(gridWidth.y)); double hdx=0.5*dx; double hdy=0.5*gridWidth.y; int numberX = (RS_Math::round((right-left) / dx) + 1); int number = 2*numberX*numberY; baseGrid.set(left+remainder(-left,dx),bottom+remainder(-bottom,fabs(gridWidth.y))); if (number<=0 || number>maxGridPoints) return; pt.resize(number); int i=0; RS_Vector bp0(baseGrid),dbp1(hdx,hdy); for (int y=0; y<numberY; ++y) { RS_Vector bp1(bp0); for (int x=0; x<numberX; ++x) { pt[i++] = bp1; pt[i++] = bp1+dbp1; bp1.x += dx; } bp0.y += gridWidth.y; } //find metaGrid if (metaGridWidth.y>minimumGridWidth && graphicView->toGuiDY(metaGridWidth.y)>2) { metaGridWidth.x=(metaGridWidth.x<0.)?-sqrt(3.)*fabs(metaGridWidth.y):sqrt(3.)*fabs(metaGridWidth.y); RS_Vector baseMetaGrid(left+remainder(-left,metaGridWidth.x)-fabs(metaGridWidth.x),bottom+remainder(-bottom,metaGridWidth.y)-fabs(metaGridWidth.y)); // calculate number of visible meta grid lines: int numMetaX = (RS_Math::round((right-left) / metaGridWidth.x) + 1); int numMetaY = (RS_Math::round((top-bottom) / metaGridWidth.y) + 1); if (numMetaX<=0 || numMetaY<=0) return; // create meta grid arrays: metaX.resize(numMetaX); metaY.resize(numMetaY); double x0(baseMetaGrid.x); for (int i=0; i<numMetaX; x0 += metaGridWidth.x) { metaX[i++] = x0; } x0=baseMetaGrid.y; for (int i=0; i<numMetaY; x0 += metaGridWidth.y) { metaY[i++] = x0; } } }
void DeviceELMOSteeringMotorVel::setProfilePosition(double jointPosition_rad, double jointVelocity_rad_s) { const double Ke = -1.0; double command_pos = remainder(jointPosition_rad,M_PI); double position_error = remainder(command_pos - getPosition(), 2*M_PI); double command_vel = Ke * position_error; if (command_vel > jointVelocity_rad_s) {command_vel = jointVelocity_rad_s;} if (command_vel <-jointVelocity_rad_s) {command_vel =-jointVelocity_rad_s;} printf("%d:Pos control: C %.2f S %.2f O %.2f\n",nodeId_,jointPosition_rad, getPosition(), command_vel); setProfileVelocity(command_vel); }
bool SailMotor::move_to_angle(float degrees, float reference, int& feedback, int& num_rounds) { float position; int target = 0; if(degrees <= 180 && degrees >= -180) { // get feedback epos_get_actual_position(AV_SAIL_NODE_ID); feedback = epos_read.node[AV_SAIL_NODE_ID-1].actual_position; position = (feedback / (AV_SAIL_TICKS_PER_DEGREE))-reference; // num_rounds = (feedback + 180 * AV_SAIL_TICKS_PER_DEGREE) / (360 * AV_SAIL_TICKS_PER_DEGREE); // num_rounds = (int)round((position+180.0*sign(position))/360.0); num_rounds = (int)round((position)/360.0); //rtx_message("num_ro: %d, feedback: %d", num_rounds, feedback); //num_rounds = (position+180.0)/360.0; position = remainder(position, 360.0); if(fabs(degrees - position) > 180.0) { num_rounds -= 1*sign(remainder((position - degrees),360.0)); } //rtx_message("pos: %f, num_ro: %d", position, num_rounds); // Go to position target = (int)round(AV_SAIL_TICKS_PER_DEGREE * (degrees + reference + num_rounds*360)); epos_set_target_position(AV_SAIL_NODE_ID, target); // rtx_message("num_ro: %d, position: %f, target: %f", num_rounds, position, target/AV_SAIL_TICKS_PER_DEGREE*1.0); //rtx_message("current: %f; %d, goal: %f; %d", position, feedback, degrees, target); epos_activate_position(AV_SAIL_NODE_ID); } else { rtx_message("WARNING: A Sail angle beyond +-180 deg has been asked for. (at %f) Skipping...", degrees); return false; } #if 0 if(degrees <= AV_MAX_SAIL_ANGLE && degrees >= -AV_MAX_SAIL_ANGLE) { // Go to position epos_set_target_position(AV_SAIL_NODE_ID,(int)round((degrees+reference)*AV_SAIL_TICKS_PER_DEGREE)); epos_activate_position(AV_SAIL_NODE_ID); // and get feedback epos_get_actual_position(AV_SAIL_NODE_ID); feedback = epos_read.node[AV_SAIL_NODE_ID-1].actual_position; } else { rtx_message("WARNING: A Sail angle beyond the max sail angle has been asked for. (at %f) Skipping...", degrees); return false; } #endif return true; }
int smallestN(double r1, double r2, double r3) { double radianEPS = 1e-7; for (int n = 3; n <= 1000; ++n) { double segmentAngle = M_PI / n; double rem1 = remainder(r1, segmentAngle); double rem2 = remainder(r2, segmentAngle); double rem3 = remainder(r3, segmentAngle); if (fabs(rem1) < radianEPS && fabs(rem2) < radianEPS && fabs(rem3) < radianEPS) return n; } return -1; }
/** * find the closest grid point *@return the closest grid to given point *@coord: the given point */ RS_Vector RS_Grid::snapGrid(const RS_Vector& coord) const { if( cellV.x<RS_TOLERANCE || cellV.y<RS_TOLERANCE) return coord; RS_Vector vp(coord-baseGrid); if(isometric){ //use remainder instead of fmod to locate the left-bottom corner for both positive and negative displacement RS_Vector vp1( vp-RS_Vector( remainder(vp.x-0.5*cellV.x,cellV.x)+0.5*cellV.x, remainder(vp.y-0.5*cellV.y,cellV.y)+0.5*cellV.y)); RS_VectorSolutions sol({vp1,vp1+cellV,vp1+cellV*0.5, vp1+RS_Vector(cellV.x,0.), vp1+RS_Vector(0.,cellV.y)}); vp1=sol.getClosest(vp); return baseGrid+vp1; }else{ return baseGrid+vp-RS_Vector(remainder(vp.x,cellV.x),remainder(vp.y,cellV.y)); } }
double handle_op_power(stack_t **args, int *is_bad_formula) { if (*args == NULL) goto error; double result = 0.0, operand1, operand2; char *front; // Get first operand front = pop_copy(args); if (front == NULL) goto error; operand1 = atof(front, cgc_strlen(front) + 1, is_bad_formula); free(front); if(*is_bad_formula) goto error; // Get second operand front = pop_copy(args); if (front == NULL) goto error; operand2 = atof(front, cgc_strlen(front) + 1, is_bad_formula); free(front); if(*is_bad_formula) goto error; if (*args != NULL) goto error; // Too many arguments if (operand2 == 0.0) result = 1.0; else if (operand2 == 1.0) result = operand1; else if (isnan(operand2)) result = operand2; else if (operand1 == 0 && operand2 > 0) result = 0.0; else if (operand1 < 0 && remainder(operand2, 1) == 0.0) result = pow(-operand1, operand2) * (remainder(operand2, 2) == 0 ? 1 : -1); else result = pow(operand1, operand2); goto done; error: clear_stack(args); *is_bad_formula = 1; result = 0.0; done: return result; }
/* Test NaN-resulting library calls. */ int test_errs() { int errs = 0; printf("Checking well-defined library errors\n"); errs += CHECK_NAN(pow(-3.0, 4.4)); errs += CHECK_NAN(log(-3.0)); errs += CHECK_NAN(sqrt(-0.001)); errs += CHECK_NAN(asin(1.0001)); errs += CHECK_NAN(sin(INFINITY)); errs += CHECK_NAN(cos(INFINITY)); errs += CHECK_NAN(acosh(0.999)); errs += CHECK_NAN(remainder(3.3, 0.0)); errs += CHECK_NAN(remainder(INFINITY, 3.3)); return errs; }
/** * @return Intersection between two lines. */ RS_VectorSolutions RS_Information::getIntersectionLineLine(RS_Line* e1, RS_Line* e2) { RS_VectorSolutions ret; if (!(e1 && e2)) { RS_DEBUG->print("RS_Information::getIntersectionLineLin() for nullptr entities"); return ret; } RS_Vector p1 = e1->getStartpoint(); RS_Vector p2 = e1->getEndpoint(); RS_Vector p3 = e2->getStartpoint(); RS_Vector p4 = e2->getEndpoint(); double num = ((p4.x-p3.x)*(p1.y-p3.y) - (p4.y-p3.y)*(p1.x-p3.x)); double div = ((p4.y-p3.y)*(p2.x-p1.x) - (p4.x-p3.x)*(p2.y-p1.y)); if (fabs(div)>RS_TOLERANCE && fabs(remainder(e1->getAngle1()-e2->getAngle1(), M_PI))>=RS_TOLERANCE*10.) { double u = num / div; double xs = p1.x + u * (p2.x-p1.x); double ys = p1.y + u * (p2.y-p1.y); ret = RS_VectorSolutions({RS_Vector(xs, ys)}); } // lines are parallel else { ret = RS_VectorSolutions(); } return ret; }
std::string CRC::runCRC(std::string message) { std::string messageString = message; //Original besked std::string poly = "111010101"; //Polynomial division std::string aug = messageString + "00000000"; //Padded besked, bliver senere til remainder indtil denne bliver checksummen std::string tempRemainderString; std::string tempAug; std::bitset<9> divisor(poly); //Bit divisor std::bitset<9> tempRemainder; //holder til besked while (aug.size() > 8) //imens beskeden er større end 8 (size of checksum!) { std::bitset<9> remainder(std::string(aug, 0, 9)); //Tag de 9 første bit if (remainder[8] == 1) //Hvis det første bit er sat (!!! Dette læses bitvist, fra højre mod venstre!!!) { tempRemainder = remainder ^ divisor; //Udfør polynomial division via "xor" tempRemainderString = tempRemainder.to_string(); tempAug = ""; tempAug.append(aug, 9, aug.size()); aug = tempRemainderString + tempAug; //Saml resultat og resterende besked } else //Hvis det første bit ikke er sat, så skal beskeden shiftes mod venstre { aug.erase(aug.begin()); //Sletter det første bit i beskeden } } //std::cout << "checksum: " << aug << std::endl; //Output checksum return aug; }
static void test_invalid(long double x, long double y) { int q; q = 0xdeadbeef; assert(isnan(remainder(x, y))); assert(isnan(remquo(x, y, &q))); #ifdef STRICT assert(q == 0xdeadbeef); #endif assert(isnan(remainderf(x, y))); assert(isnan(remquof(x, y, &q))); #ifdef STRICT assert(q == 0xdeadbeef); #endif assert(isnan(remainderl(x, y))); assert(isnan(remquol(x, y, &q))); #ifdef STRICT assert(q == 0xdeadbeef); #endif }
double sin(double x) { double a,c,z; if(!finite(x)) /* sin(NaN) and sin(INF) must be NaN */ return x-x; x=remainder(x,PI2); /* reduce x into [-PI,PI] */ a=copysign(x,one); if (a >= PIo4) { if(a >= PI3o4) /* ... in [3PI/4,PI] */ x = copysign((a = PI-a),x); else { /* ... in [PI/4,3PI/4] */ a = PIo2-a; /* rtn. sign(x)*C(PI/2-|x|) */ z = a*a; c = cos__C(z); z *= half; a = (z >= thresh ? half-((z-half)-c) : one-(z-c)); return copysign(a,x); } } if (a < small) { /* rtn. S(x) */ big+a; return x; } return x+x*sin__S(x*x); }
static void division( MLDiv const &x, MLDiv const &y, MLDiv &q, MLDiv &r ) { UBIG m; UBIG n; UBIG y1; m = length( y ); if( m == 1 ) { y1 = y.d[ m - 1 ]; if( y1 > 0 ) { quotient( q, x, y1 ); remainder( r, x, y1 ); } else { fatal( "divide by 0" ); } } else { n = length( x ); if( m > n ) { zero( q ); r = x; } else { assert( 2 <= m && m <= n && n <= w ); longdivide( x, y, q, r, n, m ); } } }
LTFAT_API int LTFAT_NAME_COMPLEX(fftrealcircshift)( const LTFAT_COMPLEX* in, ltfat_int L, const double shift, LTFAT_COMPLEX* out) { ltfat_div_t domod; double shiftLoc; int status = LTFATERR_SUCCESS; CHECKNULL(in); CHECKNULL(out); CHECK(LTFATERR_BADSIZE, L > 0, "L must be positive"); domod = ltfat_idiv(L, 2); shiftLoc = remainder(shift, L); if (shiftLoc != 0) { LTFAT_COMPLEX phasefact = -I * (LTFAT_REAL)(2.0 * M_PI * shiftLoc) / (( LTFAT_REAL) L); out[0] = in[0]; for (int ii = 1; ii < domod.quot + 1; ii++) out[ii] = exp((LTFAT_REAL)ii * phasefact) * in[ii]; } else { if (in != out) memcpy(out, in, (domod.quot + 1) * sizeof * out); } error: return status; }
int main (int argc, char* argv[]) { int code, shares; float prevCPS, currCPS,prevCPSVal, currCPSVal, percentChange; scanf("%d %d %f %f", &code, &shares, &prevCPS, &currCPS); prevCPSVal = prevCPS*shares; currCPSVal = currCPS*shares; if (prevCPSVal > 999) { double prevFloor = floor(prevCPS); double prevRem = remainder (prevCPSVal,1000); } //What percent of 12000, is 11930? //11930/12000 = .994166667 //1-.994166667 = .005833 which is almost .6% //equation, (1-(prevworth/currworth)) percentChange = ((currCPSVal-prevCPSVal)/prevCPSVal)*10; printf("%s", "Code Shares Prev CPS Curr CPS Prev Worth Curr Worth Change(%)\n"); printf("%s", "-----------------------------------------------------------------\n"); printf("%d %d $%.2f $%.2f $%.2f $%.2f %.1f\n", code, shares, prevCPS, currCPS, prevCPSVal, currCPSVal, percentChange*10); return 0; }
int main(){ int x,y; printf("Please input two integer numbers:"); scanf("%d %d",&x,&y); printf("Remainde=%d\n",remainder(x,y)); return 0; }
// ----------------------------------------------------------------------------- // SIPCodecUtils::ValueWithoutQuotes // ----------------------------------------------------------------------------- // TInt SIPCodecUtils::ValueWithoutQuotes( const TDesC8& aValue, TPtrC8& aWithoutQuotes) { if (aValue.Length() > 0) { TLex8 lex(aValue); lex.SkipSpace(); if (lex.Get() == '"') { // Remove first quote TPtrC8 remainder(aValue.Mid(1)); // Ensure that ending quote exists. if(remainder.LocateReverse('"') != (remainder.Length()-1)) { return KErrArgument; } aWithoutQuotes.Set(remainder.Left(remainder.Length()-1)); } else { return KErrArgument; } } return KErrNone; }
double cos(double x) { double a,c,z,s = 1.0; if(!finite(x)) /* cos(NaN) and cos(INF) must be NaN */ return x-x; x=remainder(x,PI2); /* reduce x into [-PI,PI] */ a=copysign(x,one); if (a >= PIo4) { if (a >= PI3o4) { /* ... in [3PI/4,PI] */ a = PI-a; s = negone; } else { /* ... in [PI/4,3PI/4] */ a = PIo2-a; return a+a*sin__S(a*a); /* rtn. S(PI/2-|x|) */ } } if (a < small) { big+a; return s; /* rtn. s*C(a) */ } z = a*a; c = cos__C(z); z *= half; a = (z >= thresh ? half-((z-half)-c) : one-(z-c)); return copysign(a,s); }
TaylorModel& TaylorModel::operator *= (const TaylorModel& other) { assert(other.time_interval_ == time_interval_); register FCL_REAL c0, c1, c2, c3; register FCL_REAL c0b = other.coeffs_[0], c1b = other.coeffs_[1], c2b = other.coeffs_[2], c3b = other.coeffs_[3]; const Interval& rb = other.r_; c0 = coeffs_[0] * c0b; c1 = coeffs_[0] * c1b + coeffs_[1] * c0b; c2 = coeffs_[0] * c2b + coeffs_[1] * c1b + coeffs_[2] * c0b; c3 = coeffs_[0] * c3b + coeffs_[1] * c2b + coeffs_[2] * c1b + coeffs_[3] * c0b; Interval remainder(r_ * rb); register FCL_REAL tempVal = coeffs_[1] * c3b + coeffs_[2] * c2b + coeffs_[3] * c1b; remainder += time_interval_->t4_ * tempVal; tempVal = coeffs_[2] * c3b + coeffs_[3] * c2b; remainder += time_interval_->t5_ * tempVal; tempVal = coeffs_[3] * c3b; remainder += time_interval_->t6_ * tempVal; remainder += ((Interval(coeffs_[0]) + time_interval_->t_ * coeffs_[1] + time_interval_->t2_ * coeffs_[2] + time_interval_->t3_ * coeffs_[3]) * rb + (Interval(c0b) + time_interval_->t_ * c1b + time_interval_->t2_ * c2b + time_interval_->t3_ * c3b) * r_); coeffs_[0] = c0; coeffs_[1] = c1; coeffs_[2] = c2; coeffs_[3] = c3; r_ = remainder; return *this; }
double angle(const V3 & u, const V3 & v) { double dot = u * v; double nu = u.normL2(); double nv = v.normL2(); return remainder(acos(dot/(nu*nv)),2*M_PI); }
extern int testremainder(void) { static double s_rd1 = 2.5; static double s_rd2 = 2.0; static double s_rd3 = 0.5; return remainder(s_rd1, s_rd2) == s_rd3; }
int main(void) { #pragma STDC FENV_ACCESS ON double y; float d; int e, i, err = 0; struct dd_d *p; for (i = 0; i < sizeof t/sizeof *t; i++) { p = t + i; if (p->r < 0) continue; fesetround(p->r); feclearexcept(FE_ALL_EXCEPT); y = remainder(p->x, p->x2); e = fetestexcept(INEXACT|INVALID|DIVBYZERO|UNDERFLOW|OVERFLOW); if (!checkexcept(e, p->e, p->r)) { printf("%s:%d: bad fp exception: %s remainder(%a,%a)=%a, want %s", p->file, p->line, rstr(p->r), p->x, p->x2, p->y, estr(p->e)); printf(" got %s\n", estr(e)); err++; } d = ulperr(y, p->y, p->dy); if (!checkcr(y, p->y, p->r)) { printf("%s:%d: %s remainder(%a,%a) want %a got %a ulperr %.3f = %a + %a\n", p->file, p->line, rstr(p->r), p->x, p->x2, p->y, y, d, d-p->dy, p->dy); err++; } } return !!err; }
GaloisFieldPolynomial& GaloisFieldPolynomial::operator%=(const GaloisFieldPolynomial& gfp) { if ((gf == gfp.gf) && (deg() >= gfp.deg()) && (gfp.deg() >= 0) ) { GaloisFieldPolynomial quotent(gf, deg() - gfp.deg() + 1); GaloisFieldPolynomial remainder(gf, gfp.deg() - 1); for(int i = deg(); i >= 0; i--) { if (i <= (int)quotent.deg()) quotent[i] = remainder[remainder.deg()] / gfp[gfp.deg()]; for(int j = remainder.deg(); j > 0; j--) { remainder[j] = remainder[j - 1] + (quotent[i] * gfp[j]); } remainder[0] = poly[i] + (quotent[i] * gfp[0]); } simplify(remainder); poly = remainder.poly; } return *this; }
int main() { float a, b, r; char op; do { printf("Extra line of code --- \n"); printf("Number operator Number: "); scanf(" %f %c %f", &a, &op, &b); switch (op) { case '+' : r = add(a,b); break; case '*' : r = product(a,b); break; case '-' : r = subtract(a,b); break; case '/' : r = divide(a,b); break; case '%' : r = remainder(a,b); break; case 'q' : break; default : op='?'; } if (op=='?') printf("Unknown operator\n"); else if (op=='q') printf("Bye\n"); else printf("%f %c %f = %f\n", a, op, b, r); } while (op != 'q'); return 0; }
// ---------------------------------------------------------------------------- // CSIPProfileSIMRecord::FindSIPSchema // ---------------------------------------------------------------------------- // TPtrC8 CSIPProfileSIMRecord::RemoveSIPSchemaL( const TDesC8& aValue ) { __ASSERT_ALWAYS (aValue.Length() > 0, User::Leave(KErrArgument)); _LIT8(KSIPAndColon, "sip:"); _LIT8(KSIPSAndColon, "sips:"); TPtrC8 schemeAndColon; TInt sipSchemePos = aValue.FindF(KSIPAndColon); if (sipSchemePos < 0) { TInt sipsSchemePos = aValue.FindF(KSIPSAndColon); if (sipsSchemePos != 0) { User::Leave (KErrArgument); } schemeAndColon.Set(KSIPSAndColon); } else { if (sipSchemePos != 0) { User::Leave (KErrArgument); } schemeAndColon.Set(KSIPAndColon); } TPtrC8 remainder(aValue.Mid(schemeAndColon.Length())); return remainder; }
void RS_ActionInfoAngle::trigger() { RS_DEBUG->print("RS_ActionInfoAngle::trigger()"); if (entity1!=NULL && entity2!=NULL) { RS_VectorSolutions sol = RS_Information::getIntersection(entity1, entity2, false); if (sol.hasValid()) { intersection = sol.get(0); if (intersection.valid && point1.valid && point2.valid) { double angle1 = intersection.angleTo(point1); double angle2 = intersection.angleTo(point2); double angle = RS_Math::rad2deg(remainder(angle2-angle1,2.*M_PI)); QString str; str.setNum(angle); str += QChar(0xB0); if(angle<0.) { QString str2; str2.setNum(angle+360.); //positive value str += QString(" or %1%2").arg(str2).arg(QChar(0xB0)); } RS_DIALOGFACTORY->commandMessage(tr("Angle: %1").arg(str)); } } else { RS_DIALOGFACTORY->commandMessage(tr("Lines are parallel")); } } }
/* Permutation Sequence The set [1,2,3,…,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, We get the following sequence (ie, for n = 3): "123" "132" "213" "231" "312" "321" Given n and k, return the kth permutation sequence. Note: Given n will be between 1 and 9 inclusive. 康拓展开 一、康托展开:全排列到一个自然数的双射 Cantor Expand X = an*(n-1)!+an-1*(n-2)!+...+ai*(i-1)!+...+a2*1!+a1*0! ai为整数,并且0<=ai<i(1<=i<=n) 适用范围:没有重复元素的全排列 二、全排列的编码: {1,2,3,4,...,n}的排列总共有n!种,将它们从小到大排序,怎样知道其中一种排列是有序序列中的第几个? 如 {1,2,3} 按从小到大排列一共6个:123 132 213 231 312 321.想知道321是{1,2,3}中第几个大的数. 这样考虑:第一位是3,小于3的数有1、2 .所以有2*2!个.再看小于第二位,小于2的数只有一个就是1 ,所以有1*1!=1 所以小于32 的{1,2,3}排列数有2*2!+1*1!=5个.所以321是第6个大的数.2*2!+1*1!是康托展开.(注意判断排列是第几个时要在康托展开的结果后+1) 三、全排列的解码 如何找出第16个(按字典序的){1,2,3,4,5}的全排列? 1. 首先用16-1得到15 2. 用15去除4! 得到0余15 3. 用15去除3! 得到2余3 4. 用3去除2! 得到1余1 5. 用1去除1! 得到1余0 有0个数比它小的数是1,所以第一位是1 有2个数比它小的数是3,但1已经在之前出现过了所以是4 有1个数比它小的数是2,但1已经在之前出现过了所以是3 有1个数比它小的数是2,但1,3,4都出现过了所以是5 最后一个数只能是2 所以排列为1 4 3 5 2 */ string getPermutation(int n, int k) { vector<int> factorial(n - 1, 1); vector<int> remainder(n - 1, 0); vector<int> remove_base(n, 0); string ans; for (int i = 0; i < n; ++i) remove_base[i] = i + 1; for (int i = 1; i < n - 1; ++i) factorial[i] = (i + 1) * factorial[i - 1]; k = k - 1; for (int i = 0; i < n - 1; ++i) { remainder[i] = k / factorial[n - 2 - i]; k = k % factorial[n - 2 - i]; } auto it = remove_base.begin(); for (int i = 0; i < n - 1; i++) { ans = ans + to_string(remove_base[remainder[i]]); remove_base.erase(it + remainder[i]); } ans = ans + to_string(remove_base[0]); return ans; }
void OperandStack::drem(){ Operand op1H, op1L, op2H, op2L; op2L = pop(); op2H = pop(); op1L = pop(); op1H = pop(); if( (op1H.type != TYPE_DOUBLE) || (op2H.type != TYPE_DOUBLE) || (op1H.type != TYPE_DOUBLE) || (op2H.type != TYPE_DOUBLE) ) { printf("Error type not double: :op_stack.drem\n"); exit(0); } double val1, val2, val3; val1 = to_double(op1H.bytes, op1L.bytes); val2 = to_double(op2H.bytes, op2L.bytes); val3 = remainder(val1, val2); op1H.set_high(TYPE_DOUBLE, &val3); op1L.set_low(TYPE_DOUBLE, &val3); push(op1H); push(op1L); /*if(size < 4) { printf("Error :op_stack.drem\n"); exit(0); } if( ( (top-1)->bytes == 0x0 ) && (top->bytes==0x0) ) { exception("ArithmeticException: / by zero at OpStack.drem"); } __opDrem(top); top-=2; size-=2;*/ }