Algoritma prima {untuk mencari bilangan prima dari suatu angka} |
Deklarasi prima : integer |
Deskripsi float sqrtn=sqrt(p) if(p<2) return 0 else if(p<4) return 1 else if(p%2==0) return 0 else for(int d=3;d<=sqrtn; d+=2) if(p%d==0) |
Listing
#include <iostream> |
#include <math.h> |
#include <conio.h> |
#include <cstdlib> |
|
|
using namespace std; |
class prima{ |
friend istream& operator>>(istream&,prima&); |
friend ostream& operator<<(ostream&,prima&) ; |
|
private: |
int a,b,z,d; |
|
public: |
int prim(int ); |
void cetak(); |
}; |
int prima::prim(int p){ |
float sqrtn=sqrt(p); |
if(p<2) |
return 0; |
else if(p<4) |
return 1; |
else if(p%2==0) |
return 0; |
Else |
for(int d=3;d<=sqrtn; d+=2) |
if(p%d==0) |
|
return 0; |
return 1; |
} |
|
|
istream& operator>>(istream& in,prima& x){ |
cout<<"MASUKKAN BILANGAN : ";in>>x.a; |
return in; |
} |
ostream& operator<<(ostream& out,prima& x){ |
|
for (int z=1;z<=x.a;z++){ |
if(x.a%z==0) |
if(x.prim(z)) |
out << z << " "; |
} |
|
return out; |
} |
|
|
int main(){ |
prima a; |
cin >> a; |
cout<<a; |
getch(); |
return 0; |
} |
Tidak ada komentar:
Posting Komentar