Project Euler #44: Pentagon numbers

Sort by

recency

|

39 Discussions

|

  • + 0 comments

    Simple solution in Python 3 :

    def p(n):
        return n*(3*n-1)//2
    def is_pentagonal(p):
        a=(1+24*p)**0.5
        return True if a==int(a) and (a+1)%6==0 else False
    n,k=map(int,input().strip().split())
    for i in range(k+1,n):
       if is_pentagonal(p(i)-p(i-k)) or is_pentagonal(p(i)+p(i-k)):
           print(p(i))
    
  • + 0 comments

    JAva code

    import java.io.*;
    import java.util.*;
    
    public class Solution {
    
      
          static Set<Long> pent = new HashSet<>();
    
        static void generate() {
            for (long n = 1; n <= 1000000; n++) {
                long temp = n * (3 * n - 1) / 2;
                pent.add(temp);
            }
        }
    
        public static void main(String[] args) {
            generate();
            Scanner scanner = new Scanner(System.in);
            long N = scanner.nextLong();
            long K = scanner.nextLong();
    
            for (long n = K + 1; n <= N; n++) {
                long diff = n * (3 * n - 1) / 2 - (n - K) * (3 * (n - K) - 1) / 2;
                long add = n * (3 * n - 1) / 2 + (n - K) * (3 * (n - K) - 1) / 2;
                
                if (pent.contains(diff) || pent.contains(add)) {
                    System.out.println(n * (3 * n - 1) / 2);
                }
            }
        }
    }
    
  • + 0 comments
    #include <bits/stdc++.h>
    using namespace std;
    #define ull unsigned long
    
    set<ull> pent;
    
    void generate() {
        ull temp;
        for(ull n = 1; n <= 1000000; n++) {
            temp = n * (3 * n - 1) / 2;
            pent.insert(temp);
        }
    }
    
    int main() {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT */
        generate();
        ull N, K;
        cin >> N >> K;
        for(ull n = K + 1; n <= N; n++) {
            ull diff = n * (3 * n - 1) / 2 - (n - K) * (3 * (n - K) - 1) / 2;
            ull add = n * (3 * n - 1) / 2 + (n - K) * (3 * (n - K) - 1) / 2;
            if(pent.count(diff) || pent.count(add)) {
                cout << n * (3 * n - 1) / 2 << endl;
            }
        }
        return 0;
    }
    

    Accurate and Perfect solution of this problme

  • + 0 comments

    ****d={}

    for i in range (1,10**6 + 1) :

    d[i]=int(i * ( 3*i - 1 ) /2)

    n,k=list(map(int,input().split())

    for i in range(k+1,n) :

    if ispentagonal(d[i]-d[i-k]) or ispentagonal(d[i]+d[i-k]) :

    print(d[i])

  • + 0 comments

    from math import sqrt :

    def ispentagonal(a) :

    if a <= 0 :
    
        return False
    
    delt = 1 + 24 * a
    x1 = (1 - sqrt(delt)) / 6
    x2 = (1 + sqrt(delt)) / 6
    
    if x1 > 0 and x1.is_integer():
        return True
    if x2 > 0 and x2.is_integer():
        return True