无法解决项目欧拉问题6 [英] Can't Solve Project Euler Problem 6

查看:89
本文介绍了无法解决项目欧拉问题6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。



我正在尝试解决项目euler网站上的问题6,但我遇到了麻烦。



这是我到目前为止的代码:



  var  square =  0 ; 
var sum = 0 ;
var result = 0 ;

for var i = 0 ; i< 101 ; i ++){
square = 数学 .pow(i, 2 );
square + = square;

sum + = i;
}

result = 数学 .pow(总和, 2 ) - 方形;
console .log(result);





我看到它,for循环开始计数并增加i,变量square首先获取i的幂,然后将其添加到自身。它一次又一次地这样做,所以最终结果应该是从1到100的所有数字到2的幂。之后变量sum计算从1到100的所有数字并将它们存储在自身中。之后,变量result将sum取为2的幂,并从square中取sum。这看起来很符合我的想法,但显然有些错误,因为我得到了错误的结果(25482500)。



有人可以向我解释我做错了什么吗? div class =h2_lin>解决方案

嗯...看看你的代码:

  for  var  i =  0 ; i <   101 ; i ++){
square = Math.pow(i, 2 < /跨度>);
square + = square;

sum + = i;
}

循环后 square 的值是多少?

答案:20,000

为什么?

因为它只使用最终值绕循环:100 - 所有其他值在下一次循环循环时被丢弃。

和100 * 100 * 2 == 20,000



您需要开始使用调试器来处理这类事情,而不是要求其他人!


Hello.

I'm trying to solve problem 6 at the project euler site, but I'm having trouble.

This is my code so far:

var square = 0;
var sum = 0;
var result = 0;

for (var i = 0; i < 101; i++){
    square = Math.pow(i, 2);
    square += square;
    
    sum += i;
}

result = Math.pow(sum, 2) - square;
console.log(result);



As I see it, the for loop starts counting and increasing i, the variable "square" first takes the power of i and then adds it to itself. It does that again and again so the final result should be all the numbers from 1 to 100 each to the power of 2. After that the variable "sum" counts all the numbers from 1 to 100 and stores them in itself. After that, the variable "result" takes "sum" to the power of 2 and substracts "sum" from "square". This seems pretty logical in my head, but apparently something's wrong as I get the wrong result (25482500).

Can someone please explain to me what I did wrong?

解决方案

Um...Look at your code:

for (var i = 0; i < 101; i++){
    square = Math.pow(i, 2);
    square += square;

    sum += i;
}

What value is in square after the loop?
Answer: 20,000
Why?
Because it only ever uses the final value to go round the loop: 100 - all other values are discarded the next time it goes round the loop.
And 100 * 100 * 2 == 20,000

You need to start using the debugger to work this kind of thing out, rather that asking other people!


这篇关于无法解决项目欧拉问题6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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