首页 \ 问答 \ 使用嵌套for循环检查数字是否为素数;(Using nested for loop to check if numbers are prime; and if so, add them to the set — WITHOUT using a method for isPrime)

使用嵌套for循环检查数字是否为素数;(Using nested for loop to check if numbers are prime; and if so, add them to the set — WITHOUT using a method for isPrime)

总结:尝试学习其他的做事方式。 我最不了解的Java部分是每段代码如何相互通信。 因此,我不是在经典的isPrime中使用方法调用来生成循环,而是尝试仅使用嵌套循环。 然而,我得到的最接近的是将它增加2到100 - 它不会检查它是否为素数。 我提供了示例代码,但我不确定为什么我的代码无法按预期工作。 如果可能,请更正我的代码示例并解释您的更正。

我正在尝试做的事情:将所有素数2 - > 100添加到集合A中(在开始之前添加了2)

预期:2,3,5,7,11,13,17,19,23,29,31 ......实际:...... 5,7,9,11,13,15,17 ...(+ = 2一直到99)

为什么这段代码只计算2,而不是使用我指定的条件?

我的逻辑是:

  1. 准备一切(创建东西,添加2来设置)
  2. condition addNumber - 如果为true,则将其添加到集合中,如果不是,则转到下一个数字
  3. 外环 - n - 是被测试的数字。 从3开始,增加2s(没有偶数将是素数),最多100
  4. 内循环 - i - “i - > n”范围用于检查是否为素数。 如果n可被i整除,则该数字不是素数
  5. 如果未发现数字违反n%i == 0,请将其添加到矢量中
  6. 如果发现违反条件,退出内循环并移动到下一个数字

我不明白为什么要休息; 我不打算工作。 我不明白为什么,即使打破某种方式不起作用,我指定终止条件也不起作用。 我不明白为什么我的支票似乎永远不会到达而且它只是添加每2个数字......

我尝试过的事情:玩弄休息和终止。 移动嵌套循环部分内外的东西。

我所能发生的一切就是它被计算为2,或者它加起来为7,然后停在它不应该添加的第一个值(9)

研究我做了:

在Java中打破嵌套循环

为什么我们检查素数的平方根以确定它是否是素数?

素数发生器逻辑

理想的答案是示例代码,修正了我的代码和解释。 我试图这样做没有使用isPrime方法,该方法的逻辑必须在添加数字的循环内。

public static void main(String[] args) {
     boolean addNumber = true; 
     for (int n = 3; n < 100; n = n+2) { //outer loop -- argument
         for(int i=2; i< n; i++){ //check if 2-->n is a divisor
             if (n % i == 0){ //if it's NOT prime 
                 addNumber = false; //set condition to FALSE
                 i=n+1; //ensure that inner loop break condition is met
                 break; //literally tell it to break
             }
             else {
                 i=n+1;
                 break; //if the above is not met, ensure that the inner loop is broken
             }

         }//closes inner loop

         //before exiting loop, add the confirmed prime number to set
         if(addNumber) //if we should add it
             A.append(n); //add it 
     }//closes outer loop

     System.out.println(A);
}

编辑:事实证明使用“休息”; 这只是效率问题 。 一旦我们确定n不是素数,为什么要继续运行所有剩余的i值? 我一直在讨论这个话题,并提出了一个实际上需要使用break的场景。

考虑:假设我们想要将前25个素数添加到集合中,而不是想要在集合中添加2到100之间的素数。

我们需要将外部循环更改为“安全”(不完全正确,但仅适用于此示例),假设n = 1000.这样,我们知道我们不会耗尽要添加的素数; 肯定有25个素数在2到1000之间。

for (int n = 3; n < 1000; n++) {
  addNumber = true;
  ....

现在我们真的需要休息! 在下面正确的代码示例(@ Nani2015)中终止外部循环之前,我们需要添加:

if(A.size() == 25 )
  break; //break out of outer loop -- we have the desired number of elements

这将检查我们正在使用的集合A是否具有我们想要的元素数量。 如果为FALSE:什么都不做。 如果为TRUE:break(我们已经完成)

希望这能澄清事情。 在我原来的问题中,使用break是完全没必要的 。 我需要做的就是删除两个中断,我的代码将按预期工作。 但是,在不正确的区域输入中断会导致问题。 “打破;” 当你希望或需要在满足终止条件之前终止循环时,应该使用它。


Summary: Attempting to learn alternative ways of doing things. The part of Java that I understand least is how each piece of code communicates with one another. As such, instead of using a method call in the classic isPrime for loop generation, I'm attempting to do so with using nested loops only. However, the closest I have gotten is to have it increment by 2 up to 100 -- it isn't checking for if it's prime. I have provided sample code, but I'm not sure why my code does not work as intended. If possible, please correct my code sample and explain your correction(s).

What I'm trying to do: add all prime numbers 2-->100 into set A (2 has been added before beginning)

Expected: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31... Actual: ...5,7,9,11,13,15,17... (+=2 all the way to 99)

Why does this code only count by 2, instead of using the condition I have specified?

My logic is:

  1. prepare everything (create stuff, add 2 to set)
  2. condition addNumber -- if true, add that to the set, if not, move on to next number
  3. outer loop -- n -- is the number being tested. start at 3, increment by 2s (no even numbers will be prime), up to 100
  4. inner loop -- i -- "i --> n" range is used for checking if prime. if n is divisible by i, the number is NOT prime
  5. if the number was not found to violate n%i==0, add it to the vector
  6. if it was found to violate the condition, exit inner loop and move onto the next number

I don't understand why break; isn't working as I intend. I don't understand why, even if break somehow won't work, me specifying the termination condition doesn't work. I don't understand why it seems like my check is never being reached and it's just adding every 2 numbers...

Things I've tried: played around with break and terminations. Moved things inside and outside of portions of the nested loops.

All I can get to have happen is for it to count by 2, or for it to add up to 7 and then stop at the first value it shouldn't add (9)

Research I've done:

Breaking out of nested loops in Java

Why do we check up to the square root of a prime number to determine if it is prime?

Prime Number Generator Logic

The ideal answer would be sample code with a correction of my code and an explanation. I am trying to do this WITHOUT using an isPrime method, the logic for that method must be inside the loop that adds the number.

public static void main(String[] args) {
     boolean addNumber = true; 
     for (int n = 3; n < 100; n = n+2) { //outer loop -- argument
         for(int i=2; i< n; i++){ //check if 2-->n is a divisor
             if (n % i == 0){ //if it's NOT prime 
                 addNumber = false; //set condition to FALSE
                 i=n+1; //ensure that inner loop break condition is met
                 break; //literally tell it to break
             }
             else {
                 i=n+1;
                 break; //if the above is not met, ensure that the inner loop is broken
             }

         }//closes inner loop

         //before exiting loop, add the confirmed prime number to set
         if(addNumber) //if we should add it
             A.append(n); //add it 
     }//closes outer loop

     System.out.println(A);
}

EDIT: It turns out using "break;" here is only a matter of efficiency. As soon as we determine that n is not a prime number, why continue running through all the remaining i values? I've continued playing around with this topic, and have come up with a scenario in which using break is actually necessary.

Consider: instead of wanting to add prime numbers between 2 and 100 to the set, let’s say we want to add the first 25 prime numbers to the set.

We need to change the outer loop to something “safe” (not exactly proper, but just for this example) let’s say n = 1000. This way, we know that we won’t run out of prime numbers to be added; there are definitely 25 prime numbers between 2 and 1000.

for (int n = 3; n < 1000; n++) {
  addNumber = true;
  ....

NOW we actually need to use break! Before terminating the outer loop in the correct code sample below (by @Nani2015), we need to add:

if(A.size() == 25 )
  break; //break out of outer loop -- we have the desired number of elements

This checks whether or not the set we are working with, A, has the amount of elements we desire. If FALSE: do nothing. If TRUE: break (we are done)

Hopefully this clarifies things. In my original question, using break was entirely unnecessary. All I needed to do was remove both breaks, and my code would have worked as intended. However, inputting breaks in incorrect areas caused issues. "break;" should be used when you wish to or need to terminate the loop prior to its termination condition being met.


原文:https://stackoverflow.com/questions/40066393
更新时间:2023-10-31 14:10

最满意答案

正如在评论中所读,我决定使用Three.js来加载对象。

Three.js具有允许加载.OBJ的功能

然后我将使用GSAP(GreenSock库)以使其移动/旋转等。


As read in comment, I decided to use Three.js in order to load the object.

Three.js has a function that permit to load .OBJ

Then I will use GSAP (GreenSock library) in order to make it move / rotate etc.

相关问答

更多

相关文章

更多

最新问答

更多
  • h2元素推动其他h2和div。(h2 element pushing other h2 and div down. two divs, two headers, and they're wrapped within a parent div)
  • 创建一个功能(Create a function)
  • 我投了份简历,是电脑编程方面的学徒,面试时说要培训三个月,前面
  • PDO语句不显示获取的结果(PDOstatement not displaying fetched results)
  • Qt冻结循环的原因?(Qt freezing cause of the loop?)
  • TableView重复youtube-api结果(TableView Repeating youtube-api result)
  • 如何使用自由职业者帐户登录我的php网站?(How can I login into my php website using freelancer account? [closed])
  • SQL Server 2014版本支持的最大数据库数(Maximum number of databases supported by SQL Server 2014 editions)
  • 我如何获得DynamicJasper 3.1.2(或更高版本)的Maven仓库?(How do I get the maven repository for DynamicJasper 3.1.2 (or higher)?)
  • 以编程方式创建UITableView(Creating a UITableView Programmatically)
  • 如何打破按钮上的生命周期循环(How to break do-while loop on button)
  • C#使用EF访问MVC上的部分类的自定义属性(C# access custom attributes of a partial class on MVC with EF)
  • 如何获得facebook app的publish_stream权限?(How to get publish_stream permissions for facebook app?)
  • 如何防止调用冗余函数的postgres视图(how to prevent postgres views calling redundant functions)
  • Sql Server在欧洲获取当前日期时间(Sql Server get current date time in Europe)
  • 设置kotlin扩展名(Setting a kotlin extension)
  • 如何并排放置两个元件?(How to position two elements side by side?)
  • 如何在vim中启用python3?(How to enable python3 in vim?)
  • 在MySQL和/或多列中使用多个表用于Rails应用程序(Using multiple tables in MySQL and/or multiple columns for a Rails application)
  • 如何隐藏谷歌地图上的登录按钮?(How to hide the Sign in button from Google maps?)
  • Mysql左连接旋转90°表(Mysql Left join rotate 90° table)
  • dedecms如何安装?
  • 在哪儿学计算机最好?
  • 学php哪个的书 最好,本人菜鸟
  • 触摸时不要突出显示表格视图行(Do not highlight table view row when touched)
  • 如何覆盖错误堆栈getter(How to override Error stack getter)
  • 带有ImageMagick和许多图像的GIF动画(GIF animation with ImageMagick and many images)
  • USSD INTERFACE - > java web应用程序通信(USSD INTERFACE -> java web app communication)
  • 电脑高中毕业学习去哪里培训
  • 正则表达式验证SMTP响应(Regex to validate SMTP Responses)