Project Euler Consecutive Prime Sum Java

I wrote a program that didn’t work for project Euler problem 50, so if you haven’t solved that one probably don’t look if you want too solve it.

the problem is linked here:https://projecteuler.net/problem=50

Spoiler to answer below

My answer was 997661, which was exactly ten more than the real solution

My program seems to function to me, but I am inexperienced and was hoping that a more experienced programmer could find what was wrong.

import java.util.ArrayList;

public class ConsecutivePrimeSum {

public static void main (String() args){
    ArrayList<Integer> primes = new ArrayList<Integer>();
    for(int i = 2; i < 1000000; i++){
        if( isPrime(i)){primes.add(i);}
    }
    int total = 0;
    int counter = 0;


    while(total + primes.get(counter) < 1000000){
        total += primes.get(counter);
        System.out.println(primes.get(counter));
        counter += 1;
    }
    System.out.println(total + " " + counter);
}

public static boolean isPrime(Integer number){
    int sqrt = (int)Math.sqrt(number) + 1;
    for(int i = 2; i < sqrt; i++){
        if(number % i == 0 && number != i){return false;}
    }
    return true;
}

}

performance – Project Euler #645 — speed up Monte-Carlo simulation in Python

I am trying to solve Q645. While the logic used for my code seems to be appropriate, the code itself is way too slow for the large number required in this question. May I ask for suggestion(s) to improve my code’s performance?

The question is as in the link: https://projecteuler.net/problem=645

My Python code is as follow:

def Exp(D):
    day_list = (0)*D
    num_emperor = 0
    while all((d == 1 for d in day_list)) == False:
        #the birthday of the emperors are independent and uniformly distributed throughout the D days of the year
        bday = np.random.randint(0,D)
        day_list(bday) = 1
        num_emperor+=1
        #indices of d in day_list where d == 0
        zero_ind = (i for i,v in enumerate(day_list) if v == 0)
        for ind in zero_ind:
            try:
                if day_list(ind-1) and day_list(ind+1) == 1:
                    day_list(ind) = 1
            except IndexError:
                if ind == 0:
                    if day_list(-1) and day_list(1) == 1:
                        day_list(0) = 1
                elif ind == len(day_list)-1:
                    if day_list(len(day_list)-2) and day_list(0) == 1:
                        day_list(len(day_list)-1) = 1
    return num_emperor

def my_mean(values):
    n = 0
    summ = 0.0
    for value in values:
        summ += value
        n += 1
    return summ/n

def monte_carlo(iters, D):
    iter = 0
    n_emperor = 0
    while iter < iters:
        n_emperor = Exp(D)
        yield n_emperor
        iter += 1

avg_n_emperor = my_mean(monte_carlo(iters,D))
print(avg_n_emperor)

And my logic is as follow:

For the day_list inside the Exp(D) function, where D is the number of days in a year, zeros mean no holiday, and ones mean holiday. Initially the day_list is all zeros since there is no holiday to begin with.

The rules of defining a random day (d) as a holiday is as follow:

  1. At the beginning of the reign of the current Emperor, his birthday is declared a holiday from that year onwards.

  2. If both the day before and after a day d are holidays, then d also becomes a holiday.

I then subsequently implement the rules stated for the question, to gradually add holidays (ones) into the day_list. After num_emperor number of emperors, all the days (d) in day_list will become 1, i.e. all days will become holiday. This is the point to quit the while_loop in Exp(D) function and count the number of emperors required. To get the average number of emperors required for all the days to become holidays (avg_n_emperor), I then apply the monte-carlo method.

For my current code, the time takes is as follow:

avg_n_emperor = my_mean(monte_carlo(iters=100000,D=5)) #6-7 seconds

avg_n_emperor = my_mean(monte_carlo(iters=1000000,D=5)) #about 62 seconds

in which the time takes increase approx. linearly with the iters.

However,

avg_n_emperor = my_mean(monte_carlo(iters=1000,D=365)) #about 68 seconds

already takes about 68 seconds, and the question is asking for D=10000. Not to mention that the iters required for the answer to be accurate within 4 digits after the decimal points (as required by the question) would be much larger than 1000000 too…

Any suggestion(s) to speed up my code would be appreciated! 🙂

Projeto euler nº10 C++

O objectivo aqui é encontrar a soma de todos os primos abaixo de um certo n.
Até ao n<5 consigo encontrar a soma, 2 + 3 que é 5, mas depois seja qualquer for o n acima de 5 vai-me sempre dar 5.
Já estou a a olhar para isto há algumas horas e não consegui perceber ainda, se alguém me conseguisse dar uma luzinha agradecia imenso.

///

int main(){
    
int n;
int i;
int a=0;
int soma=0;

for (n=2;n<6;n++){

     for(i=2;i<n;i++){

        if(n%i==0){
            a++;
        }
            
     }

     if(a==0){
        soma += n;
        a=0;
     }

    
 }
    
cout<< soma;      

}

///
Obrigado.

Peço desculpa pela má apresentação da pergunta, primeira vez.

unity – Using Euler angles to rotate object 360 degrees

I’m trying to create script that rotates object in given axis by set amount of degrees.

That’s my 2 core methods

public Vector3 rotation;

public void RotateDegreesFast ()
{
    transform.DOLocalRotate (GetTargetRotation (), rotationTime);
}

private Vector3 GetTargetRotation ()
{
    Vector3 newRotation = new Vector3 (
        rotation.x + transform.localEulerAngles.x,
        rotation.y + transform.localEulerAngles.y,
        rotation.z + transform.localEulerAngles.z)

    return newRotation;
}

I was using this script for a little while, it was working perfectly in Y and Z axis. Now I try to rotate object 45 degrees in X axis (rotation = new Vector3(45f, 0f, 0f)). It works until rotation in x value equals 135. Transform.localEulerAngles.x is returning 45 instead of 135. So it’s stuck between 90 and 135 degrees. I was trying to use transform.localRotation.eulerAngles.x instead, but it doesn’t work as well.

I am aware this works that way because specific Euler angle can be represented in many ways. I also know that DOTween has DOLocalRotateQuaternion method, but the thing is that this component is often reused by a designer that sets value of rotation variable in the inspector. It’s way easier to use Euler angles for him.

real analysis – Calculating $int_0^1frac{ln^2xln(1-x)}{1-x}dx$ without using Beta function and Euler sum.

Is it possible to show that

$$int_0^1frac{ln^2xln(1-x)}{1-x}dx=-frac12zeta(4)$$

without using the Beta function

$$text{B}(a,b)=int_0^1 x^{a-1}(1-x)^{b-1}dx=frac{Gamma(a)Gamma(b)}{Gamma(a+b)}$$
and the generalized Euler sum

$$sum_{n=1}^infty frac{H_n}{n^q}= left(1+frac{q}{2} right)zeta(q+1)-frac{1}{2}sum_{k=1}^{q-2}zeta(k+1)zeta(q-k),quad qge 2 ?$$

By integration by parts I found

$$int_0^1frac{ln^2xln(1-x)}{1-x}dx=color{blue}{int_0^1frac{ln^2(1-x)ln x}{x}dx}$$

Setting $1-xto x$ gives the blue integral again.

This integral seems tough under such restrictions. All approaches are welcome.

thanks.

dg.differential geometry – Existence results for Lagrangian solutions to the Incompressible Euler Equation?

It is known that if a function (which we shall call the lagrangian flow, or lagrangian trajectory) $$X:(mathbb{R}/mathbb{Z})^3 times (0,T) to mathbb{R}^3$$ with $X in H^1_t$ (i.e. has weak time derivatives $v=partial_tX in L^2((mathbb{R}/mathbb{Z})^3times (0,T))$) minimises the energy lagrangian $$L(X)=int_{(mathbb{R}/mathbb{Z})^3 times (0,T)} v^2$$ subject to $X(cdot,0),X(cdot,T)$ fixed, and $X(cdot,t)$ being a $textbf{volume preserving}$ diffeomorphism of $(mathbb{R}/mathbb{Z})^3$ for each $t$,

then $u(cdot,t)=v(cdot,t) circ X(cdot,t)^{-1}$ is a weak solution to the incompressible Euler equation $$dot{u} + nabla cdot (uu) = nabla p, nabla cdot u = 0$$ in a distributional sense.

My question is about existence results once $X(cdot,0),X(T,cdot)$ are fixed, and depends on what we mean by diffeomorphisms:

  1. if we require $X(0,t)$ to be $C^{infty}$ volume preserving diffeomorphisms for each $t$, can we guarantee the existence of a minimiser?

  2. if we require $X(0,t)$ to be $C^1$ volume preserving diffeomorphisms for each $t$, again, can we guarantee the existence of a minimser?

  3. I expect both of the above answers are no or at least unknown, since I’ve found no mention of them in the literature I’ve read. The case I’m therefore really interested in is when by ‘diffeomorphism’ we only require that $$X(cdot,t) text{ is bijective, and measure preserving}$$ Correct me if I’m wrong but the above theory still holds even in this loose definition. Can we now, i.e. in the loosest sense, get existence of minimisers? Perhaps with some conditions on $X(cdot,0)$ and $X(cdot,T)$? Anything known, perhaps some papers, about this case would be appreciated.

programming challenge – Project Euler 67 | Maximum sum path II reading from file

I tried to solve the Problem Euler 67 with golang, because I started to study Go recently.

This is my solution:

package main

import (
    "flag"
    "fmt"
    "io/ioutil"
    "os"
    "strconv"
    "strings"
    "time"
)

func calculateMaxPath(trianglePointer *()()int, lines int) int {
    trisums := make(()()int, lines)
    triangle := *trianglePointer

    for row := lines - 1; row > -1; row-- {
        trisums(row) = make(()int, row+1)
        for col := 0; col < row+1; col++ {
            if row == lines-1 {
                trisums(row)(col) = triangle(row)(col)
            } else {
                if trisums(row+1)(col) > trisums(row+1)(col+1) {
                    trisums(row)(col) = triangle(row)(col) + trisums(row+1)(col)
                } else {
                    trisums(row)(col) = triangle(row)(col) + trisums(row+1)(col+1)
                }
            }
        }
    }

    return trisums(0)(0)
}

func openFile() (*()()int, int) {
    flag.Parse()

    ifile := flag.Arg(0)

    if len(ifile) == 0 {
        println("No File Specified")
        os.Exit(1)
    }

    content, err := ioutil.ReadFile(ifile)

    if err != nil {
        println("Error reading", ifile)
        os.Exit(1)
    }

    strRows := strings.Split(string(content), "n")
    content = nil

    lines := 0
    for i := len(strRows) - 1; i > 0; i-- {
        if lines == 0 && strRows(i) != "" {
            lines = i + 1
            break
        }
    }

    var strs ()string

    pyramid := make(()()int, lines)
    for row := 0; row < lines; row++ {
        strs = strings.Fields(strRows(row))
        pyramid(row) = make(()int, len(strs))

        for col := 0; col < len(strs); col++ {
            pyramid(row)(col), _ = strconv.Atoi(strs(col))
        }
    }

    return &pyramid, lines
}

func main() {
    start := time.Now()

    pyramid, lines := openFile()

    greatestSum := calculateMaxPath(pyramid, lines)

    fmt.Printf("nTotal sum: %v, Elapsed time: %vn", greatestSum, time.Since(start))
}

What could be a better approach? Coud I use go routines to increase performance?

at.algebraic topology – Euler characteristic with compact support of spaces of Euclidean lattices

Thanks for contributing an answer to MathOverflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

Use MathJax to format equations. MathJax reference.

To learn more, see our tips on writing great answers.

analytic number theory – Convergence of Euler product and Dirichlet series in the same half-plane?

I’m crossposting this from math.stackexchange because I think it might be inappropriately research-level for the community over there.

Suppose we have an Euler product over the primes

$$F(s) = prod_{p} left( 1 + frac{a_p}{p^s} right)^{-1},$$

where each $a_p in mathbb{C}$. The Euler product is convergent in the range $Re(s) > sigma_c$, and absolutely convergent in the range $Re(s) > sigma_a$, for some $sigma_c < sigma_a in mathbb{R}$. If we multiply out the Euler product, we get a Dirichlet series

$$F(s) = sum_{n=1}^infty frac{a_n}{n^s},$$

where $a_n := prod_{p^k || n} a_p^k$ is completely multiplicative as a function of $n$.

Question: We know that the Dirichlet series for $F(s)$ must converge absolutely in the half-plane $Re(s) > sigma_a$. Must the Dirichlet series for $F(s)$ also converge in the half-plane $Re(s) > sigma_c$? If not, what is a counterexample?

My question is motivated by considering a product like

$$F(s) = left(1 – frac{1}{2^s}right)^{-1}left(1 + frac{1}{3^s}right)^{-1}left(1 – frac{1}{5^s}right)^{-1}left(1 + frac{1}{7^s}right)^{-1} … = prod_{n=1}^infty left( 1 + frac{(-1)^n}{p_n^s} right)^{-1},$$

where a classical result on infinite products demonstrates convergence for $Re(s) > 1/2$ (although absolute convergence only happens in the half-plane $Re(s) > 1$). This product for $F(s)$ will have no zeroes in the half-plane $Re(s) > 1/2$, so if we multiply it out to get the Dirichlet series

$$F(s) = sum_{n=1}^infty frac{a_n}{n^s} = 1 + frac{1}{2^s} – frac{1}{3^s} + frac{1}{4^s} + frac{1}{5^s} – frac{1}{6^s} – frac{1}{7^s}…,$$

does the Dirichlet series converge too? Can we then conclude that the coefficients $a_n$ satisfy

$$sum_{j = 1}^n a_j = O(n^{1/2 + epsilon}),$$

for all $epsilon > 0$?

nt.number theory – Could computing the next prime in a finite Euler product be made rigorous?

It is well known that:

$$zeta(s):=prod_{n=1}^{infty} frac{1}{1-p_n^{-s}} qquad Re(s) gt 1$$

with $p_n =$ the $n$-th prime. It also known that:

$$zeta(2n):= frac{(-1)^{n+1} B_{2n}(2pi)^{2n}}{2(2n)!}$$

where $B_{2n}$ is the $2n$-th Bernoulli number.

Now define the function:

$$f(k,N,x):= zeta(2k) – left(prod_{n=1}^{N} frac{1}{1-p_n^{-2k}}right)cdot left(frac{1}{1-x^{-2k}}right) qquad Re(s) gt 1$$

where $k, N in mathbb{N}$ and $x$ is the unknown next prime ($p_{N+1}$) to be computed.

I found numerically that solving $x$ in $f(k,N,x)=0$ for some $N$, yields an increasingly accurate approximation of $p_{N+1}$ when $k$ increases. For example take the first 6 primes and try to derive the 7th prime (17):

$f(6, 6, x) = 0 rightarrow x = 16.64054…$

$f(12, 6, x) = 0 rightarrow x = 16.95214…$

$f(24, 6, x) = 0 rightarrow x =16.99830…$

The key question is how high $k$ needs to go to ensure that $x=p_{N+1}$ after rounding. In the following Maple code, I simply used $k=2N$ and it already correctly generates all ‘next’ primes up to $N=60$:

Digits:=600
for N from 1 to 60 do ithprime(N), ithprime(N+1), round(fsolve(f(2*N, N, x), x = 0 .. 300)) end do

I immediately acknowledge that this is a highly inefficient and impractical algorithm to generate primes. However, is there more to say about the minimally required value of $k$ (maybe as a function of $N$) to ensure that rounding $x$ will correctly yield $p_{N+1}$?