Informatică, întrebare adresată de danamocanu71, 8 ani în urmă

Se dau n numere naturale.Calculati suma obtinuta prin adunarea celui mai mare divizor prim a fiecarui numar dat.(C++)

Răspunsuri la întrebare

Răspuns de ArMyFoRHeLL
4
#include <iostream>

using namespace std;
int cmmdp(int x)
{
    int d = 2;
    while (x != 1)
    {
        while (x%d == 0)
            x = x / d;
        d = d + 1;
    }
    return d - 1;
}
int main()
{
    int n, x, i, S = 0;
    cin >> n;
    for (i = 0; i<n; i++)
    {
        cin >> x;
        S = S + cmmdp(x);
    }
    cout << S<<endl;
  
    return 0;
}



ArMyFoRHeLL: Aici ai o optimizare in cazul care un numar citit e prim
ArMyFoRHeLL: #include <iostream>

using namespace std;
int prim(int x)
{
if(x%2==0 && x!=2)
return 0;
for(int i=3;i*i<=x;i=i+2)
if(x%i==0)
return 0;
return 1;
}
int cmmdp(int x)
{
int d = 2;
if(prim(x))
return x;
while (x != 1)
{
while (x%d == 0)
x = x / d;
d = d + 1;
}
return d - 1;
}
int main()
{
int n, x, i, S = 0;
cin >> n;
for (i = 0; i<n; i++)
{
cin >> x;
S = S + cmmdp(x);
}
cout << S <<endl;

return 0;
}
Răspuns de Rayzen
7
#include <iostream>
using namespace std;

int main()
{
   int n, x,S=0;
   cout<<"Introduceti numarul de numere: ";
   cin>>n;
   for(int i=1;i<=n;i++)
   {
       cin>>x;
       for(int d=x/2;d>1;d--)
       {
           if(x%d == 0)
           {
               int prim=1;
               for(int d2 = 2; d2<=d/2;d2++)
               {
                   if(d % d2 == 0)
                   {
                       prim=0; break;
                   }
               }
               if(prim == 1)
               {
                   S = S + d;
                   break;
               }
           }
       }
   }
   cout<<"Suma este: "<<S;
}
Alte întrebări interesante