求一个数的平方根以及判断一个数是否为素数(or质数)

最近开始啃Robert Sedgewick与Kevince Wayne著的《算法》,是由我的一个师弟给我强推的!
里面是Java语言,但自己只会点C++。所以慢慢自己学习写成C++ code.
今天是补上前些天刚看了些的内容,先从简单学起!

Day1–>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Suit up!
1. 求一个数的平方根sqrt.cpp:
用到了牛顿迭代法;

/*************************************************************************
	> File Name: sqrt.cpp
	> Author: MAQ
	> Mail: maq046@163.com
	> Created Time: 2019年04月21日 星期一 12时43分46秒
 ************************************************************************/

#include<iostream>
#include<cmath>
using namespace std;
int main (){
    cout << "Please enter a number: "<<endl;
    double a;
    cin >>a;
    double results=a;
    double err=0.00000001;
    if (a<0){
        cerr<< " Please input the non-negative number!!"<<endl;
    }
    else {
        while (abs(results-a/results)>err){
            results=(results+a/results)/2;
        }
        cout << "The square root of "<<a<<" is "<<results<<endl;
    }
    return 0;
}

g++ sqrt.cpp
./a.out

Please enter a number:
26
The square root of 26 is 5.09902

2. 判断一个数是否为素数? isPrime.cpp

#include<iostream>
using namespace std;
int main(){
    cout <<"Please enter a number: "<<endl;
    int a;
    cin >>a;
    if (a<2){
        cerr <<"Wrong Number!!"<<endl;
    }
    else{
        bool flag;
        for (int i=2;i*i<=a;i++){
            if (a%i==0){
                flag=false;
                break;
            }
            flag=true;
        }
        if (flag==false){
            cout << a<< " is not a Prime!!"<<endl;
        }
        else{
            cout << a<< " is a Prime!!"<<endl;
        }
    }
    return 0;
}

g++ isPrime.cpp

./a.out

Please enter a number:
25
25 is not a Prime!!

./a.out

Please enter a number:
31
31 is a Prime!!

/今日标签/

活在当下:感受指尖的阳光,品味手中的奶盖乌龙,聆听一首轻快的歌。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值