Problems encountered in the problem and solutions


Preface

Record clever methods and commonly used functions encountered in practice


One, find prime numbers

Part of the code is as follows (example):

#include <stdio.h>
#define MAXS 10001
int main(){
    
    
int sushu[MAXS]={
    
    2},flag,i,j,cnt;
//第一个素数是2放在sushu【0】,剩余位置都为0;
for(cnt = 1, i = 3; cnt < MAXS; i += 2){
    
    
//剩下的数从3开始判断,偶数肯定不是素数,所以i+=2;
    for(j = 0; flag = ((sushu[j] * sushu[j]) <= i); j ++) {
    
    
    //质数的乘积一定不是质数,i不能整除比它小的所有质数;
        if(!(i % sushu[j]))break;//i能整除比它小的质数则i不是质数
    }//当sushu中已知素数判断完成后,sushu【j】=0,跳出循环;
    if(!flag)sushu[cnt ++] = i;//flag==0时把i加入素数;
}
}

Second, determine whether the string is a number

Part of the code is as follows (example):

#include<string>
#include<sstream>
bool isNum(string str){
    
    
	stringstream sin(str);//利用string流类库
	double t;
	char c;
	if(!(sin>>t))	return false;//如果不能传入double型则返回false
	if(sin>>c)	return false;//如果转换字符成功,则说明str中包含字符,例如123k2,
	/*t中存入123,sin流中为k2,c中为k*/
	else	return true;//str为纯数字
}

to sum up

This method is much simpler than the two for loops that we thought at the beginning and continues to judge, and it takes less time to find high prime numbers. (1. Prime number) is written by the blogger https://blog.csdn.net/dadaxiongdebaobao/article/details/51193809, here is a summary of the notes.

Guess you like

Origin blog.csdn.net/jiaoooooo/article/details/112688168