Jump to content
em

[c++] Vedeti vreo optimizare?

Recommended Posts

Posted

Nu era lent, doar avea buguri. Evita sa mai compari inturi cu floaturi sau sa rescrii functii care sunt deja in standard.


#include<iostream>
#include<math.h>
using namespace std;

double li=1,ls;
int curs=1; //cursor pentru a putea lucra cu 10^-k

void sqrt(int n,float a,int prec){
double zec,i;
do{
zec=1.0/curs; //stabilim zecimala la care lucram
for(i=li; ;i+=zec) //cautam
{
//cout<<"Acum sunt la "<<pow(i,n)<<a<<pow(i+zec,n)<<endl;
if(pow(i,n)<=a && a<=pow(i+zec,n)){ //am gasit
/* Actualizam, sloboz */
li=i;
ls=i+zec;

/* Actualizam, sloboz */
curs*=10; //are valori doar puteri ale lui 10 (pentru a calcula 10^-k, duh! )
prec--;
break; //ciclul nu mai are rost, am gasit zecimala, ne-am facut treaba, la revedere
}
}
}while(prec>=0); //folosesc variabila prec pe post de cursor, sa stiu la a cata zecimala sa ma opresc
}

int main(){
int n,prec;float a;

cout<<"Bun venit la emisiunea \" Calculeaza radical de ordin n din a, cu o prezicie de x zecimale !\" Have fun \n";
cout<<"a=";cin>>a;
cout<<"n=";cin>>n;
cout<<"x="; cin>>prec;
sqrt(n,a,prec);

cout<<li<<" < "<<"Radical de ordinul "<<n<<" din "<<a<<" < "<<ls<<endl;;
return 0;
}

Ca sa intelegi unde greseai ruleaza codul asta



#include <stdio.h>
int main()
{
double a = 0.6;
double b = 2025.0;
printf("a * b = %f\n", a * B);
printf("a * b = (int) %d\n", (int) (a * B));
return 0;
}

Surprinzator. Nu?

  • Upvote 1
Posted

Inca imi mention pozitia ca merge mult mai rapid (i.e. sirul converge rapid). In plus nu e ca si cum nth root nu se poate deduce din algoritmul pentru square root. E destul de straight forward.

  • Upvote 1

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...