几个简单数论的算法的实现

这学期上C++,无聊,技术又太烂,什么都做不了,所以就随便把一些算法用C++实现了,算法还是很经典的哈,不要应为我引用了,就不屑了哈~

素数的那两个是有点缺陷的哈,聪明的你一定可以发现哈^_^

 语言:C++

编译环境:VS2008

//求两个数的最大公约数
#include <iostream>

using namespace std;

int gcd(int a, int b)
{
 int g;
 if(b == 0)
  g = a;
 else
  g = gcd(b,a%b);
 return g;
}

int main()
{
 int a, b;
 cout << "请输入两个整数" << endl;
 cin >> a >> b;
 cout << gcd( a, b) << endl;
 system("pause");
 return 0;
}

 

//求两个数的最小公倍数
#include <iostream>

using namespace std;

int lcm(int a, int b)
{
 int temp, l;
 if(a < b)
 {
  temp = a;
  a = b;
  b = a;
 }
 l = a;
 while(l%b)//源程序是l%b > 0;
 {
  l += a;
 }
 return l;
}
int main()
{
 int a, b;
 cout << "请输入两个整数:" << endl;
 cin >> a >> b;
 cout << lcm(a, b) <<endl;
 system("pause");
 return 0;
}

 

//判断小范围内一个数是否为质数(素数)
#include <iostream>
#include <math.h>

using namespace std;

int prime(int n)
{
 int i;
 bool flag;
 for(i=2; i<sqrt((double)n); i++)
 {
  if(n%i == 0)
  {
   flag = false; break;
  }
  flag = true;
 }
 return flag;
}

int main()
{
 int n;
 cout << "请输入一个大于1的整数:" << endl;
 cin >> n;
 cout << prime(n) << endl;
 system("pause");
 return 0;
}

 

//判断LongInt范围内的数是否是素数(包含求50000以内的素数表)
#include <iostream>
#include <math.h>

using namespace std;

int main()
{
 long i, j, l, t;
 long pr[50000];
 bool a[50000], flag;
 a[1] = false;
 i = 2;
 while(i < 50000)
 {
  if(a[i])
   j = i * 2;
  while(j < 5000)
  {
   a[j] = false;
   j += i;
  }
  i++;
 }
 l = 0;
 for(i=1; i<50000; i++)
 {
  if(a[i])
   pr[l] = i;
  l++;
 }
 cin >> t;
 flag = false;
 for(i=0; i<l; i++)
 {
  if(pr[i] >= t)
   break;
  else
  {
   if(t%pr[i] == 0)
   {
    cout << flag << endl;
    system("pause");
    exit(0);
   }   
  }
 }
 flag = true;
 cout << flag << endl;
 system("pause");
 return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值