如何显示所有素数的总和以及可在1到50之间被3整除的数字。 [英] How do I display the sum of all the prime numbers along with the numbers which are divisible by 3 between 1 to 50.

查看:155
本文介绍了如何显示所有素数的总和以及可在1到50之间被3整除的数字。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

找到素数和可被3整除的数字



我尝试过的事情:



find sum of prime numbers and the numbers divisible by 3

What I have tried:

package Day1.Examples;

public class sumofprime1to50 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		{
	        int sum=0,i,k,j;
	        for(i=2;i<50;i++)
	        {
	            k=0;
	            for(j=2;j<i;j++)>
	            {
	                if(i%j==0||i%3==0)
	                {
	                    k=1;
	                    break;
	                }
	            }
	            if(k==0)
	            {
	                sum=sum+i;
	            }
	        }
	        System.out.println("Sum = "+sum);
	    }
	}
}

推荐答案

我担心你得到素数之和,但不是数字可被3整除。

首先:

你应该学会尽快使用调试器。而不是猜测你的代码在做什么,现在是时候看到你的代码执行并确保它完成你期望的。



调试器允许你跟踪执行逐行检查变量,你会看到它有一个停止做你期望的点。

调试器 - 维基百科,免费的百科全书 [ ^ ]

掌握Visual Studio 2010中的调试 - A初学者指南 [ ^ ]

http: //docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html [ ^ ]

https://www.jetbrains.com/idea/help/debugging-your -first-java-application.html [ ^ ]



按顺序进行一些小数学分析:

- 3是唯一的数字可以被3和素数整除。所以你可以安全地分开两个任务。

计算可被3整除的数字可能过于简单。

I fear you get the sum of primes, but not number divisible by 3.
So first of all:
You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

A little mathematical analyze is in order:
- 3 is the only number divisible by 3 and prime. So you can safely separate both quests.
Counting numbers divisible by 3 can be over easy.
for(i=2;i<50;i++)
{
    if(i%3==0)
    {
        sum=sum+i;
    }
}



小心思考,你得到


With a little thinking, you get

for(i=3;i<50;i+=3)
{
    sum=sum+i;
}



有了更多的思考,你可以看到总和是


And with more thinking, you can see that the sum is

sum= 3+ 6+ 9+ 12+ 15+ 18 ...



哪个


Which is

sum= 3* (1+ 2+ 3+ 4+ 5+ 6 ...)



数学系列(1+ 2+ 3+ 4+ 5+ 6。 ..)是众所周知的,可以在没有循环的情况下计算。 (作为练习留下)


the mathematical series (1+ 2+ 3+ 4+ 5+ 6 ...) is well known and can be computed without a loop. (left as exercise)


这篇关于如何显示所有素数的总和以及可在1到50之间被3整除的数字。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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