- Sử dụng constructor để tìm số nguyên tố
[bg_collapse view=”button-red” color=”#ffffff” icon=”arrow” expand_text=”Xem bài giải” collapse_text=”Ẩn bài giải” ]
/**
* Cafedev.vn - Kênh thông tin IT hàng đầu Việt Nam
*
* @author cafedevn
* Contact: cafedevn@gmail.com
* Fanpage: https://www.facebook.com/cafedevn
* Instagram: https://instagram.com/cafedevn
* Twitter: https://twitter.com/CafedeVn
* Linkedin: https://www.linkedin.com/in/cafe-dev-407054199/
*/
#include<iostream>
#include<conio.h>
using namespace std;
class songuyento
{
int a, k, i;
public:
songuyento(int x)
{
a = x;
}
void calculate()
{
k = 1;
{
for(i = 2;i <= a / 2;i + +)
if(a % i == 0)
{
k = 0;
break;
}
else
{
k = 1;
}
}
}
void show()
{
if(k == 1)
cout << "\n\tA la so nguyen to. ";
else
cout << "\n\tA khong la so nguyen to.";
}
};
int main()
{
int a;
cout << "\n\tNhap so: ";
cin >> a;
songuyento obj(a);
obj.calculate();
obj.show();
return 0;
}
[/bg_collapse]
2. Tính giai thừa bởi sử dụng copy constructor
[bg_collapse view=”button-red” color=”#ffffff” icon=”arrow” expand_text=”Xem bài giải” collapse_text=”Ẩn bài giải” ]
/**
* Cafedev.vn - Kênh thông tin IT hàng đầu Việt Nam
*
* @author cafedevn
* Contact: cafedevn@gmail.com
* Fanpage: https://www.facebook.com/cafedevn
* Instagram: https://instagram.com/cafedevn
* Twitter: https://twitter.com/CafedeVn
* Linkedin: https://www.linkedin.com/in/cafe-dev-407054199/
*/
#include<iostream>
#include<conio.h>
class copy
{
int var, fact;
public:
copy(int temp)
{
var = temp;
}
double calculate()
{
fact = 1;
for(int i = 1;i <= var;i + +)
{
fact = fact * i;
}
return fact;
}
};
int main()
{
int n;
std:: cout << "\n\tNhap so : ";
std:: cin >> n;
copy obj(n);
copy cpy = obj;
std:: cout << "\n\t Giai thua cua " << n << "la: " << obj.calculate();
std:: cout << "\n\t Giai thua cua " << n << "la: " << cpy.calculate();
return 0;
}
[/bg_collapse]