请帮我理解这个 [英] Please help me understand this

查看:92
本文介绍了请帮我理解这个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我是编程新手,刚刚从Brian Overland C ++学习C ++而不用担心。我试着理解一切,我不读它。我试着去了解所有这些。我到了这个地方我们检查一个数字是否是素数。我真的不明白这一部分。

Hello guys, Im new to programming and just learning C++ from book by Brian Overland C++ without fear.I try to understand everything and i dont just read it.I try to understand all of it.I got to this part where we check if a number is a prime number.I really dont understand this part.

i = 2
while (i <= sqrt(n))
{
    if (n % i == 0)
    is_prime = false;
    i++;
}





所以,我在这里不明白为什么我们要检查我是否低于n的sq?不知道为什么,但我只是无法理解这个循环。我已经看到了更复杂的程序,可以理解更复杂的循环,但我只是无法理解这一点。如果有人可以向我解释它是如何工作的。请为我糟糕的英语。



so, what i dont understand here is why do we check if i is lower than sqrt of n?I dont know why but i just cant understand this loop.I've seen more complicated programs and could understand more complicated loops, but i just cant understand this.Please if someone could just explain to me how it works.Sorry for my bad English.

推荐答案

因为一旦你到达平方根,你就找到了所有可能的因素(如果有的话)。

我遇到问题虽然这个实现,因为它将重新计算循环的每个循环的平方根,这是浪费。
Because once you get to the square root, you have found all the possible factors (if any).
I take issue with that implementation though, because it will recalculate the square root on each cycle of the loop, and that's wasteful.


例如,取25号.25的平方根是5.所以任​​何数字在6到24之间不会划分25.因此不需要为这些额外数字运行循环。



假设这里n = 19,平方根19为4.35889894或4为整数。

循环将运行i = 2,3, 4.(仅3次)。否则你需要从2到18运行它,这显然是浪费时间。

For example, take number 25. square root of 25 is 5. So any number between 6 to 24 will not divide 25. so no need run loop for these extra numbers.

Suppose here n=19, square root of 19 is 4.35889894 or 4 as integer.
loop will run i=2,3,4.(only 3 times). otherwise you need to run it from 2 to 18 that is clearly wastage of time.
i = 2
while (i <= sqrt(n))
{
    if (n % i == 0){
        is_prime = false;
        break;           // break the loop if number is not prime.
    }
    i++;
}





因此,通过使用sqrt(n),您可以使程序执行得更快。



So by using sqrt(n) you can make your program execute faster.

{
	int n;
	int ind = 0;
	int i = 2;
	cout<<"Type in number you want to check"<<endl;
	cin>>n;
	while(i<n)
	{
		if(n%i==0)
		ind++;
		i++;
	}
	if(ind==0)
	{
		cout<<"This is prime number"<<endl;
	}

		else
		{
		 cout<<"This is not prime number"<<endl;
	}


这篇关于请帮我理解这个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆