![](/img/trans.png)
[英]Why does this not work when trying to find the sum of all multiples of 3 and 5 in 1000?
[英]find the sum of the multiples of 3 and 5 below 1000
好的,伙計們,所以我正在做歐拉計划挑戰,我不敢相信我被困在第一個挑戰上。 盡管我的代碼看起來很實用,但我真的不明白為什么我得到了錯誤的答案:
import java.util.ArrayList;
public class Multithree {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> x = new ArrayList<Integer>();
ArrayList<Integer> y = new ArrayList<Integer>();
int totalforthree = 0;
int totalforfive = 0;
int total =0;
for(int temp =0; temp < 1000 ; temp++){
if(temp % 3 == 0){
x.add(temp);
totalforthree += temp;
}
}
for(int temp =0; temp < 1000 ; temp++){
if(temp % 5 == 0){
y.add(temp);
totalforfive += temp;
}
}
total = totalforfive + totalforthree;
System.out.println("The multiples of 3 or 5 up to 1000 are: " +total);
}
}
我得到的答案是 266333,它說這是錯誤的......
您應該對兩者使用相同的 for 循環以避免重復計算兩者的倍數。 比如 15,30...
for(int temp =0; temp < 1000 ; temp++){
if(temp % 3 == 0){
x.add(temp);
totalforthree += temp;
}else if(temp % 5 == 0){
y.add(temp);
totalforfive += temp;
}
}
從數學的角度來看,
您沒有考慮 3 和 5 之間的公因數。
因為有重復計算。
例如; 數 15 , 30 , 45 , 60 , 75 , 90 , 105 , 120 , 135 , 150 , 165 , 180 , 195 , 210 , 225 , 240 , 3 5, 3, 5, 3, 5, 3, 5, 3, 5, 3, 5, 3, 5, 3, 5, 3, 5, 255, 3, 5, 3, 0 ,390,405,420,435,450,465,480,495,510,525,540,555,570,585,600,615,630,645,660,675,690,705,720,735,750 、 765 、 780 、 795 、 810 、 825 、 840 、 855 、 870 、 885 、 900 、 915 、 930 、 945 、 960 、 975 、 90 是公因數。
公因數的總和 = 33165。
你的答案是 266333
正確答案是 233168。
你的答案 - 公因數總和
266333-33165=233168。
(這是獲取公因數和公因數總和的代碼)
public static void main(String[] args) {
System.out.println("The sum of the Common Factors : " + getCommonFactorSum());
}
private static int getCommonFactorSum() {
int sum = 0;
for (int i = 1; i < 1000; i++) {
if (i % 3 == 0 && i % 5 == 0) {
sum += i;
System.out.println(i);
}
}
難道你們都認為不是使用循環來計算倍數的總和,我們可以使用簡單的算術級數公式輕松計算 n 項的總和來計算 n 項的總和。
我使用循環和公式評估了結果。 循環對短數據范圍非常有用。 但是當數據范圍增長超過 10 10程序需要幾個小時來處理循環的結果。 但是當使用簡單的算術級數公式時,同樣以毫秒為單位評估結果。
我們真正需要做的是:
算法:
這是我的博客文章CodeForWin - Project Euler 1: Multiples of 3 and 5中的 Java 代碼片段
n--; //Since we need to compute the sum less than n.
//Check if n is more than or equal to 3 then compute sum of all divisible by
//3 and add to sum.
if(n>=3) {
totalElements = n/3;
sum += (totalElements * ( 3 + totalElements*3)) / 2;
}
//Check if n is more than or equal to 5 then compute sum of all elements
//divisible by 5 and add to sum.
if(n >= 5) {
totalElements = n/5;
sum += (totalElements * (5 + totalElements * 5)) / 2;
}
//Check if n is more than or equal to 15 then compute sum of all elements
//divisible by 15 and subtract from sum.
if(n >= 15) {
totalElements = n/15;
sum -= (totalElements * (15 + totalElements * 15)) / 2;
}
System.out.println(sum);
如果您使用的是 Java 8,則可以通過以下方式進行:
Integer sum = IntStream.range(1, 1000) // create range
.filter(i -> i % 3 == 0 || i % 5 == 0) // filter out
.sum(); // output: 233168
要計算可被3
和5
整除的數字兩次,您可以將上述行寫兩次或.map()
2 * i
值:
Integer sum = IntStream.range(1, 1000)
.filter(i -> i % 3 == 0 || i % 5 == 0)
.map(i -> i % 3 == 0 && i % 5 == 0 ? 2 * i : i)
.sum(); // output: 266333
我如何解決這個問題是我取了一個整數值(初始化為零)並繼續添加 i 的增量值,如果它的模數 3 或 5 給我零。
private static int getSum() {
int sum = 0;
for (int i = 1; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum += i;
}
}
return sum;
}
我這樣做了好幾次。 完成 Java 所需代碼的最快、最干凈和最簡單的方法是:
public class MultiplesOf3And5 {
public static void main(String[] args){
System.out.println("The sum of the multiples of 3 and 5 is: " + getSum());
}
private static int getSum() {
int sum = 0;
for (int i = 1; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum += i;
}
}
return sum;
}
如果有人建議減少代碼行數,請告訴我您的解決方案。 我是編程新手。
int count = 0;
for (int i = 1; i <= 1000 / 3; i++)
{
count = count + (i * 3);
if (i < 1000 / 5 && !(i % 3 == 0))
{
count = count + (i * 5);
}
}
其他人已經指出了您代碼中的錯誤,但是我想補充一點,模數運算符解決方案並不是最有效的.
更快的實現將是這樣的:
int multiply3_5(int max)
{
int i, x3 = 0, x5 = 0, x15 = 0;
for(i = 3; i < max; i+=3) x3 += i; // Store all multiples of 3
for(i = 5; i < max; i+=5) x5 += i; // Store all multiples of 5
for(i = 15; i < max; i+=15) x15 += i; // Store all multiples 15;
return x3+x5-x15;
}
在這個解決方案中,我不得不取出 15 的倍數,因為 3 和 5 有 15 的倍數,所以在第二個循環中它會添加已經在第一個循環中添加的 15 的倍數;
時間復雜度為O(1)
解決方案
另一個更好的解決方案(時間復雜度為O(1)
)是如果您采用數學方法。
您正在嘗試對所有數字求和 3 + 6 + 9 ... 1000 和 5 + 10 + 15 +20 + ... 1000 這與 3 * (1 + 2 + 3 + 4 + ... + 333) 和 5 * ( 1 + 2 + 3 + 4 + ... + 200),'n' 個自然數的總和是 (n * (n + 1)) (source ) 所以你可以在一個常數時間內計算,如下:
int multiply3_5(int max)
{
int x3 = (max - 1) / 3;
int x5 = (max - 1) / 5;
int x15 = (max - 1) / 15;
int sn3 = (x3 * (x3 + 1)) / 2;
int sn5 = (x5 * (x5 + 1)) / 2;
int sn15 = (x15 * (x15 + 1)) / 2;
return (3*sn3) + (5 *sn5) - (15*sn15);
}
運行示例:
public class SumMultiples2And5 {
public static int multiply3_5_complexityN(int max){
int i, x3 = 0, x5 = 0, x15 = 0;
for(i = 3; i < max; i+=3) x3 += i; // Store all multiples of 3
for(i = 5; i < max; i+=5) x5 += i; // Store all multiples of 5
for(i = 15; i < max; i+=15) x15 += i; // Store all multiples 15;
return x3 + x5 - x15;
}
public static int multiply3_5_constant(int max){
int x3 = (max - 1) / 3;
int x5 = (max - 1) / 5;
int x15 = (max - 1) / 15;
int sn3 = (x3 * (x3 + 1)) / 2;
int sn5 = (x5 * (x5 + 1)) / 2;
int sn15 = (x15 * (x15 + 1)) / 2;
return (3*sn3) + (5 *sn5) - (15*sn15);
}
public static void main(String[] args) {
System.out.println(multiply3_5_complexityN(1000));
System.out.println(multiply3_5_constant(1000));
}
}
輸出:
233168
233168
簡直了
public class Main
{
public static void main(String[] args) {
int sum=0;
for(int i=1;i<1000;i++){
if(i%3==0 || i%5==0){
sum+=i;
}
}
System.out.println(sum);
}
}
您正在計算一些數字兩次。 您需要做的是在一個 for 循環中添加,並使用 if-else 語句,如果您找到 3 的倍數,則也不會將它們計入 5。
if(temp % 3 == 0){
x.add(temp);
totalforthree += temp;
} else if(temp % 5 == 0){
y.add(temp);
totalforfive += temp;
}
上面給出的邏輯顯示錯誤答案,因為計算時采用 3 和 5 的倍數。 在上面的邏輯中遺漏了一些東西,即 15、30、45、60……是 3 的倍數,也是 5 的倍數。那么我們在添加時需要忽略這些。
public static void main(String[] args) {
int Sum=0, i=0, j=0;
for(i=0;i<=1000;i++)
if (i%3==0 && i<=999)
Sum=Sum+i;
for(j=0;j<=1000;j++)
if (j%5==0 && j<1000 && j*5%3!=0)
Sum=Sum+j;
System.out.println("The Sum is "+Sum);
}
好的,所以這不是最好看的代碼,但它完成了工作。
public class Multiples {
public static void main(String[]args) {
int firstNumber = 3;
int secondNumber = 5;
ArrayList<Integer> numberToCheck = new ArrayList<Integer>();
ArrayList<Integer> multiples = new ArrayList<Integer>();
int sumOfMultiples = 0;
for (int i = 0; i < 1000; i++) {
numberToCheck.add(i);
if (numberToCheck.get(i) % firstNumber == 0 || numberToCheck.get(i) % secondNumber == 0) {
multiples.add(numberToCheck.get(i));
}
}
for (int i=0; i<multiples.size(); i++) {
sumOfMultiples += multiples.get(i);
}
System.out.println(multiples);
System.out.println("Sum Of Multiples: " + sumOfMultiples);
}
}
如果數字是 10,那么 3 的倍數是 3,6,9,5 的倍數是 5,10 總和是 33,程序給出相同的答案:
package com.parag;
/*
* @author Parag Satav
*/
public class MultipleAddition {
/**
* @param args
*/
public static void main( final String[] args ) {
// TODO Auto-generated method stub
ArrayList<Integer> x = new ArrayList<Integer>();
ArrayList<Integer> y = new ArrayList<Integer>();
int totalforthree = 0;
int totalforfive = 0;
int number = 8;
int total = 0;
for ( int temp = 1; temp <= number; temp++ ) {
if ( temp % 3 == 0 ) {
x.add( temp );
totalforthree += temp;
}
else if ( temp % 5 == 0 ) {
y.add( temp );
totalforfive += temp;
}
}
total = totalforfive + totalforthree;
System.out.println( "multiples of 3 : " + x );
System.out.println( "multiples of 5 : " + y );
System.out.println( "The multiples of 3 or 5 up to " + number + " are: " + total );
}
}
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t>0){
int sum = 0;
int count =0;
int n = sc.nextInt();
n--;
System.out.println((n/3*(6+(n/3-1)*3))/2 + (n/5*(10+(n/5-1)*5))/2 - (n/15*(30+(n/15-1)*15))/2);
t--;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.