gpt4 book ai didi

java - 在 LeetCode 质数挑战赛中找不到我的程序的修复程序

转载 作者:行者123 更新时间:2023-12-04 00:55:08 24 4
gpt4 key购买 nike

我尝试了多种方法来更改 LeetCode 中的代码,但找不到修复方法,挑战是下一个:

<<计算小于非负数 n 的素数数量。

示例:

输入:10输出:4说明:小于 10 的素数有 4 个,分别是 2、3、5、7。>>

我的提案代码是下一个:

 import java.util.Scanner;
class Solution {
public int countPrimes(int n) {
Scanner sc = new Scanner(System.in);
int sum = 0;
int cont = 0;
int prime = 0;
prime = sc.nextInt();
int a[] = new int [prime];
for(int i = 0; i < a.length; i++) {
a[i] = i;
cont = 0;

for(int y = 1; y< a.length; y++) {
if(a[i] % y == 0) {
cont ++;
}
}
if (cont == 2) {
sum ++;
}
}
return sum;
}
}

同时错误标记如下:

Submission Result: Compile Error More Details 
Line 7: error: cannot find symbol [in __Driver__.java] int ret = new Solution().countPrimes(param_1); ^ symbol: method countPrimes(int) location: class Solution
Run Code Status: Runtime Error
×
Run Code Result:
Your input
10
Your answer
java.util.NoSuchElementException
at line 937, java.base/java.util.Scanner.throwFor
at line 1594, java.base/java.util.Scanner.next
at line 2258, java.base/java.util.Scanner.nextInt
at line 2212, java.base/java.util.Scanner.nextInt
at line 8, Solution.countPrimes
at line 54, __DriverSolution__.__helper__
at line 84, __Driver__.main
Show Diff
Runtime: N/A

请帮忙!

最佳答案

这也会通过:

public class Solution {
public static final int countPrimes(int n) {
// mapping for if the number is divisible by prime numbers, which would make that number a composite number
boolean[] notPrime = new boolean[n];
// counting prime numbers
int count = 0;

for (int i = 2; i < n; i++) {
// If the index of notPrime would be false, we have a prime number, we go through the if, otherwise we continue
if (notPrime[i] == false) {
// Increment the number of prime numbers
count++;

// Look into future numbers
for (int j = 2; i * j < n; j++) {
// find composite numbers and set their indices to true
notPrime[i * j] = true;
}
}
}

return count;
}
}

引用文献

关于java - 在 LeetCode 质数挑战赛中找不到我的程序的修复程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63067398/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com