[英]Write a program to calculate the sum of the factorials of the first n positive integers?
[英]Program to print first m prime numbers in the first n positive integers
编写一个程序,生成并打印前 n 个正整数中的前 m 个素数。
示例:n=10,m=2 在 1-10 个自然数的范围内,我必须生成 m=2(2 个正素数) 输入:10 2 Output:2 3
我的代码:注意=尝试在 java 中回答
import java.util.Scanner;
class Main5{
static Scanner sc=new Scanner(System.in);
static boolean isPrime(int n){
//since 0 and 1 is not prime return false.
if(n==1||n==0) return false;
//Run a loop from 2 to n-1
for(int i=2; i<=n/2; i++){
// if the number is divisible by i, then n is not a prime number.
if(n%i==0)return false;
}
//otherwise, n is a prime number.
return true; }
public static void main (String[] args)
{
int n=sc.nextInt();
int m=sc.nextInt();
//check for every number from 1 to N
for(int i=1; i<=n; i++){
if(i==m){
break;
}
//check if current number is prime
if(isPrime(i)) {
System.out.print(i + " ");
}
}
}
}
使用另一个变量来保存您已经找到的素数的数量。 每当您打印质数时,都会增加其值。 当计数变量primeFound==m
从循环中中断。
还尝试在isPrime
function 中使用条件i*i<=n
,因为这会将运行时间从O(n/2)
减少到O(√n)
) 。 您还可以使用Eratosthenes 筛来预计算素数。
代码应该是这样的:
import java.util.Scanner;
class Main5{
static Scanner sc=new Scanner(System.in);
static boolean isPrime(int n){
//since 0 and 1 is not prime return false.
if(n<2) return false;
//Run a loop from 2 to n-1
for(int i=2; i*i<=n; i++){
// if the number is divisible by i, then n is not a prime number.
if(n%i==0)return false;
}
//otherwise, n is a prime number.
return true; }
public static void main (String[] args)
{
int n=sc.nextInt();
int m=sc.nextInt();
int primeFound=0;
//check for every number from 1 to N
for(int i=1; i<=n; i++){
if(primeFound==m){
break;
}
//check if current number is prime
if(isPrime(i)) {
primeFound++;
System.out.print(i + " ");
}
}
}
}
您可以使用该方法,但对于大数来说它会很慢,并且您必须为每个质数查询执行该代码。 如果您有能力和时间,也许您可以考虑这种技术: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.