Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-4041-

Solve using your language of choice

Name: Anonymous 2011-04-13 9:05

http://i56.tinypic.com/9qlh52.png

my solution in Java

import java.io.*;
import java.util.*;

public class ProblemF {
   
    public static void main(String[] args) throws Exception {
        BufferedReader fileIn = new BufferedReader(new FileReader("f.in"));
       
        String line = null;
        while ((line = fileIn.readLine()) != null) {
            int number = Integer.parseInt(line);
            if (number <= 0 || number >= 100000000) {
                break;
            }
            System.out.println(number +" : "+ getOrderedPairs(number));
        }
    }
   
    public static String getOrderedPairs(int number) {
        StringBuffer buff = new StringBuffer();
       
        int pairCount = 0;
        for (int i = 1; i <= number; i++) {
            for (int j = i; j <= number; j++) {
                int sum = getSummation(i, j);
                if (sum == number) {
                    pairCount++;
                    buff.append(" ("+ i +","+ j +")");
                    break;
                } else if (sum > number) {
                    break;
                }
            }
        }
       
        buff.insert(0, pairCount +" :");
       
        return buff.toString();
    }
   
    public static int getSummation(int tempA, int tempB) {
        int a = tempA - 1;
        int b = tempB;
        int sumB = ((b * (b + 1)) / 2);
        int sumA = ((a * (a + 1)) / 2);
        return sumB - sumA;
    }
   
}

Name: Anonymous 2011-04-13 10:01

>>1
Something like:


(defun func (string &optional acc)
  (if lst
    (loop for x from 0 to (1- (length array))
    for i in array do
      (if (eq i ":")
         (func (cdr lst) (cons (aref (1- x) array) acc))))
     acc))


Kinda, that should PROBABLY do it, I haven't tested it though.

Name: >>2 2011-04-13 10:02


Oh wait, I just looked at the first input -> output sample. Silly me ~

Name: Anonymous 2011-04-13 10:21

~:x' : 'x),1>{.),1>\{[.;]+}+/}%{~),>{+}*x=},.,2$@{'('\','*') '}%

Name: Anonymous 2011-04-13 10:21

At first I wrote a naive solution like you, but noticed it was SLOW AS FUCK even when I cranked up the optimization settings:

(asdf:oos 'asdf:load-op '#:iterate)
(use-package '#:iterate)

(declaim (optimize (speed 3) (safety 0)))

(declaim (inline sum-to))
(defun sum-to (a b)
  (declare (fixnum a b))
  ; (loop for i from a to b sum i) ; naive/slow
  (the fixnum (/ (- (* b (1+ b)) (* a (1- a))) 2))
  ;(the fixnum (/ (* (1+ (- b a)) (+ b a)) 2))
  )

;; too slow O(n*n), starts being unusable at ~10^6, when it takes longer than a minute per number
(defun find-all-sums (x)
  (iter outer (for i from 1 to x)
                   (iter (for j from i to x)
                     (when (= (sum-to i j) x)
                       (in outer (collect (print (list i j))))))))

Name: >>5 2011-04-13 10:23

So I wrote this instead:

;; instead we use some math and make it O(n)
(defun find-all-sums (x)
  (sort
   (remove-duplicates
    (iter (with 2x = (* 2 x))
          (for i from x downto 1)
          (for (values div mod) = (truncate 2x i))
          (when (zerop mod)           
            (let* ((a (/ (1- (+ div i)) 2))
                   (b (- (max div i) a)))
              (collect (list b a)))))
    :key #'first)
   #'< :key #'first))


Let's test it on the highest number:

CL-USER> (time (find-all-sums 99999999))
Evaluation took:
  1.469 seconds of real time
  1.468750 seconds of total run time (1.468750 user, 0.000000 system)
  100.00% CPU
  3,541,887,882 processor cycles
  0 bytes consed
 
((309 14145) (592 14154) (4999 14999) (5002 15000) (6539 15580)
 (9877 17249) (10224 17450) (11669 18334) (18347 23164) (19859 24379)
 (28337 31669) (31672 34685) (39319 41784) (40307 42715) (43894 46115)
 (54097 55914) (61464 63069) (65604 67110) (75447 76760) (80487 81719)
 (89454 90564) (109557 110465) (121244 122065) (124132 124934)
 (151879 152535) (164714 165319) (228092 228529) (243104 243514)
 (329882 330184) (364827 365100) (456512 456730) (494949 495150)
 (504952 505149) (684859 685004) (729859 729995) (990049 990149)
 (1010052 1010150) (1369827 1369899) (1515119 1515184) (3030287 3030319)
 (4545444 4545465) (5555547 5555564) (9090904 9090914) (11111107 11111115)
 (16666664 16666669) (33333332 33333334) (49999999 50000000)
 (99999999 99999999))


Much better!

Formatting and user input is up to you (I'm not doing your homework) as it's easy enough to implement.

Name: Anonymous 2011-04-13 10:37


(struct output (n p c)
  #:property prop:custom-write
  (λ (o p _)
    (fprintf p "~a : ~a : " (output-n o) (output-p o))
    (for-each (λ (x) (display x p) (display #\space p)) (output-c o))))

(define (solve n)
  (let ((l (for/list ((a (in-range 0 (add1 n)))
                      #:when #t
                      (b (in-range 0 (add1 n)))
                      #:when (= (Σ values a b) n)
                      (k #(#f)))
             (cons a b))))
    (output n (length l) l)))

(solve 9)
: 9 : 3 : (2 . 4) (4 . 5) (9 . 9)

Name: >>5 2011-04-13 10:37

And some testing:

(defun test-it (n)
  (every (lambda (x) (= x n)) (mapcar (lambda (list) (apply #'sum-to list)) (find-all-sums n))))

;; will print any number where the sum a to b is not equal to what it should be
(loop for i from 1 to 99999999 unless (test-it i) do (print i))


This revealed a bug when handling even numbers, hence the revised version:

(defun find-all-sums (x &aux (2x (* 2 x)))
  (sort
   (remove-duplicates
    (iter (for i from 2x downto 1)
          (for (values div mod) = (truncate 2x i))
          (and (zerop mod)
               (not (zerop (mod div 2)))
               (let* ((a (/ (1- (+ div i)) 2))
                      (b (- (max div i) a)))
                 (collect (list b a)))))
    :key #'first)
   #'< :key #'first))

Name: >>7 2011-04-13 10:38

Also, it's SLOW AS FUCK, >>6's better.

Name: Anonymous 2011-04-13 10:39

>>7
Is this fast enough for large numbers? O(n*n) solution is too slow for x = 10^8-1.

Name: Anonymous 2011-04-13 10:44

Name: Anonymous 2011-04-13 10:45

Even faster solutions would be possible using a faster factorization algorithm, but it's just a toy program, so I don't see the need to go that far.

Name: Anonymous 2011-04-13 11:08


import Control.Applicative
orderedPair x = [(a,b) | (a,b) <- liftA2 (,) [0..x] [0..x], sum [a..b] == x]


Is that what you mena?

Name: Anonymous 2011-04-13 11:12


import Control.Applicative
orderedPairs x = [(a,b) | (a,b) <- liftA2 (,) [1..x] [1..x], sum [a..b] == x]

Name: Anonymous 2011-04-13 11:17

>>13-14
Looks dead.

Name: Anonymous 2011-04-13 11:20

>>15
I know what u mena.

Name: Anonymous 2011-04-13 11:21

>>15
you mean drop dead gorgeous?

Name: Anonymous 2011-04-13 11:43


import Control.Applicative

main = interact (unlines . map (format . orderedPairs . check . read) . lines)

check x
    | x < 0 || x > 100000000 = error "you mena haskal?"
    | otherwise = x

orderedPairs x = (x, [(a,b) | (a,b) <- liftA2 (,) [1..x] [1..x], sum [a..b] == x])

format (x,ps) = show x ++ " : " ++ show (length ps) ++ " : " ++ (unwords . map (\(a,b) -> "(" ++ show a ++ "," ++ show b ++ ")")) ps


improved it to do the whole task

Name: Anonymous 2011-04-13 11:43

>>13
No. This is what I mena.
orderedPairs n = [(a, b)| a<-[1..n], b<-[a..n], sum [a..b] == n]

Name: Anonymous 2011-04-13 11:45


import Control.Applicative

main = interact (unlines . map (format . orderedPairs . check . read) . lines)

check x
    | x <= 0 || x > 100000000 = error "you mena haskal?"
    | otherwise = x

orderedPairs x = (x, [(a,b) | (a,b) <- liftA2 (,) [1..x] [1..x], sum [a..b] == x])

format (x,ps) = show x ++ " : " ++ show (length ps) ++ " : " ++ (unwords . map (\(a,b) -> "(" ++ show a ++ "," ++ show b ++ ")")) ps

Name: Anonymous 2011-04-13 11:46

>>19
right, stupid me

Name: Anonymous 2011-04-13 11:49


main = interact (unlines . map (format . orderedPairs . check . read) . lines)

check x
    | x <= 0 || x > 100000000 = error "you mena haskal?"
    | otherwise = x

orderedPairs n = (n, [(a,b) | a <- [1..n], b <- [a..n], sum [a..b] == n])

format (x,ps) = show x ++ " : " ++ show (length ps) ++ " : " ++ (unwords . map (\(a,b) -> "(" ++ show a ++ "," ++ show b ++ ")")) ps

Name: Anonymous 2011-04-13 11:49

>>21
stop bumping this shit you goddamned autistic moron

Name: Anonymous 2011-04-13 11:54

>>23
does my autism offend your anus?

Name: Anonymous 2011-04-13 12:06

>>23-24
Stop with this `'autism'` shit.

Name: Anonymous 2011-04-13 13:00

>>8
Pig disgusting Lisp-2 mod.

>>13-22
See >>10

#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>

static void solve(uint_fast32_t n)
{
  uint_fast32_t a, b, x;
  a=b=x=0;
  while(b<=n) {
    if(x == n) {
      printf("%"PRIuFAST32", %"PRIuFAST32"\n", a, b);
    }
    if(x >= n) {
      x-=a;
      a++;
    } else {
      b++;
      x+=b;
    }
  }
}

int main(int argc, char **argv)
{
  if(argc != 2) {
    fprintf(stderr, "Usage: %s n\n", argv[0]);
    return EXIT_FAILURE;
  }

  uint_fast32_t n;
  if(sscanf(argv[1], "%"SCNuFAST32, &n) != 1) {
    fprintf(stderr, "\"%s\" is not a valid number\n", argv[1]);
    return EXIT_FAILURE;
  }

  solve(n);
}


$ gcc -v 2>&1 | tail -n1
gcc version 4.5.2 20110127 (prerelease) (GCC)
$ gcc -std=c99 -Wall -Wextra -O3 -march=native solve.c -o solve
$ time ./solve 99999999 > /dev/null

real    0m0.273s
user    0m0.233s
sys    0m0.013s


$ clang --version | head -n1
clang version 2.9 (tags/RELEASE_29/final)
$ clang -std=c99 -Wall -Wextra -O3 -march=native solve.c -o solve
$ time ./solve 99999999 > /dev/null

real    0m0.446s
user    0m0.420s
sys    0m0.007s


It seems llvm spilled some registers in the inner loop. gcc just repeats a CMP (CMP/JCC/CMP/JCC -> CMP/JCC/JCC, maybe not even faster).

Name: >>5 2011-04-13 13:13

>>26
Why hate on mod and truncate? x86 does it the same, it puts quotient in eax and remainder in edx.

Name: Anonymous 2011-04-13 13:22

>>26

#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>

static void solve(uint_fast32_t n)
{
  uint_fast32_t a, b, x;
  a=b=x=0;
  while(b<=n) {
    if(x == n) {
      printf("%"PRIuFAST32", %"PRIuFAST32"\n", a, b);
    }
    if(x >= n) {
      x-=a;
      ++a;
    } else {
      ++b;
      x+=b;
    }
  }
}

int main(int argc, char **argv)
{
  if(argc != 2) {
    fprintf(stderr, "Usage: %s n\n", argv[0]);
    return EXIT_FAILURE;
  }

  uint_fast32_t n;
  if(sscanf(argv[1], "%"SCNuFAST32, &n) != 1) {
    fprintf(stderr, "\"%s\" is not a valid number\n", argv[1]);
    return EXIT_FAILURE;
  }

  solve(n);
}


Optimized.

Name: Anonymous 2011-04-13 13:44

>>27
I meant that mod means two different things in the fragment

          (and (zerop mod)
               (not (zerop (mod div 2)))


which greatly confused me.

Name: Anonymous 2011-04-13 14:14

>>29
Oh, I see... I do like abusing my Lisp-2 like that.

Name: Anonymous 2011-04-13 20:23


open System

let orderedPairs x = List.rev [ for b = x downto 1 do
                                    for a = b downto 1 do
                                        if (List.sum [a..b]) = x then yield (a, b) ]
let numbers =
    let rec getNumbers x =
        if (0 < x) && (x < 100000000) then x :: getNumbers(int(Console.ReadLine()))
        else []
    getNumbers(int(Console.ReadLine()))

let rec orderedPairsString orderedPairsX =
    match orderedPairsX with
    | (a, b) :: t -> "(" + string(a) + ", " + string(b) + ") " +  orderedPairsString(t)
    | [] -> ""

numbers
|> List.map (fun x -> (x, orderedPairs x))
|> List.map (fun (x, orderedPairsX) -> (x, List.length orderedPairsX, orderedPairsX))
|> List.map (fun (x, orderedPairsXLength, orderedPairsX) ->
                Console.WriteLine("{0} : {1} : {2}",
                                    x, orderedPairsXLength, orderedPairsString orderedPairsX))
|> ignore

ignore(Console.ReadKey())

Name: Anonymous 2011-04-13 20:47

What point in finding those pairs? They help to increase cow milking or make aircraft materials more reliable?

Name: Anonymous 2011-04-13 20:48

>>32
It's a toy problem for toy languages. That is why this thread is full of Haskell and ML.

Name: Anonymous 2011-04-13 21:15

in brainfuck
++++++++[->++++<]>>>++++++[<++++++>-]<++++[->+>
+>+<<<]>>++++>+>,.<<<<.>>>>>++++++++[-<------>]
<[->+>>>+>>>+<<<<<<<]+>+<[>[->+>+<<]>>>[->+>+<<
]>[-<+<+>>]<<+<[-<+>>>>>-<<<<]>[->>>[-<+>>>+<<]
<[->+<]<<]>>>[-]>[->-->+<<]+>[[-]<[-]>]<[[-]+++
+++++++++[-<<<++++<<<++++>>>>>>]<<<<<<<<<<.>>>>
+.-<<<.>>>>>>.<<<<<.<<<.>>>>>>>>>>>++++++++++++
[-<<<----<<<---->>>>>>][-]]>>[-<<+>>]<<<<<<<<->
+<[->[-]>+<<]>>[-<<+>>]<[[-]>>->+<[->[-]>+<<]>>
[-<<+>>]<[[-]<<<<<[-]>>>>>]<[-<<<+>>>>+<]>[-<+>
]<<<]<<]

http://codepad.org/NdgW7mgP
well, it actually solves for only a single digit but algorithm is correct. It just requires a little extra work for inputting and printing multiple digit numbers

Name: Anonymous 2011-04-13 21:45

What I came up with:

tr :: Int -> Int
tr n = n * (n-1) `div` 2
untr :: Int -> Int
untr n' = let n = fromIntegral n' in ceiling $ sqrt (n*2)

f :: Int -> [(Int, Int)]
f n = [(a,b) | b <- [2..n], let b' = tr (b+1), let a' = (b'-n), let a = untr a', tr a == a']

main = do x <- readLn
          print $ f x
          main


Not as good as some of the solutions here, but it solves the biggest case in half the needed time.

Name: Anonymous 2011-04-14 0:58

>>31

OMGOPTIMISED!


open System

let sumAtoB(a, b) = ((a - b - 1) * (a + b)) / -2

let orderedPairs x =
    [ for b = 1 to x do
        let rec checkFrom(n) =
            if n < 1 then []
            elif sumAtoB(n, b) > x then []
            elif sumAtoB(n, b) = x then (n, b) :: checkFrom(n - 1)
            else checkFrom(n - 1)
        yield checkFrom(b) ] |> List.concat
   
let numbers =
    let rec getNumbers x =
        if (0 < x) && (x < 100000000) then x :: getNumbers(int(Console.ReadLine()))
        else []
    getNumbers(int(Console.ReadLine()))

let rec orderedPairsString orderedPairsX =
    match orderedPairsX with
    | (a, b) :: t -> "(" + string(a) + ", " + string(b) + ") " +  orderedPairsString(t)
    | [] -> ""

numbers
|> List.map (fun x -> (x, orderedPairs x))
|> List.map (fun (x, orderedPairsX) ->
                Console.WriteLine("{0} : {1} : {2}",
                                    x, List.length orderedPairsX, orderedPairsString orderedPairsX))
|> ignore

ignore(Console.ReadKey())

Name: Anonymous 2011-04-14 4:18

use v6;
my @G := [\+] 0 .. *;

sub ranges( $t ) {
    my @S;
   
    for 1 .. $t.sqrt +1 -> $mag {
    my $gval = @G[ $mag ];
    my $x = ( $t - $gval ) / $mag;

    if 0 <= $x && $x.Rat.denominator == 1 {
        @S.unshift: [ $x +1, $x + $mag ];
    }
    }

    return @S;
}

for (open 'f.in').lines -> $t {
    return unless 0 < $t <= 100_000_000;

    my @out = $t.fmt: '%d';
    my @S = ranges $t;
 
    @out.push: @S.elems.fmt: ': %d :';
    for @S { @out.push: sprintf('(%d,%d)', $_[0], $_[1]) };

    @out.join(' ').say;
}

Name: Anonymous 2011-04-14 17:02

[i]bampu[/i[

Name: Anonymous 2011-04-14 17:02

AAAAAAAAAAAARRRRRRRRRGGGGGGGGGGGGGHHHHHHHHHHHHHHHHH, NOOOOO, My first BBCode Fail.

Name: Anonymous 2011-04-14 17:08

>>39
U FAIL AT BBCODE LOL

Name: Anonymous 2011-04-14 17:15

>>40
[b]U FAIL AT MAKING FUN OF PEOPLE LOL[/b[

Name: Anonymous 2011-04-14 17:24

>>2,4-8,13-14,18,20,22,31,34-37

gtfo

this is /prog/, not /toy/

>>1,26,28

you can stay.

Name: Anonymous 2011-04-14 17:28

>>1,26,28,42-43

samefag

Name: Anonymous 2011-04-14 17:44

>>28 's algorithm in HASKAL (about 3 times slower than C)

import Data.List (foldl')
import System.Environment (getArgs)

fst4 (t, _, _, _) = t

orderedPairs :: Int -> [(Int,Int)]
orderedPairs m =
    fst4 $ foldl' (\ (xs, s, a, b) n ->
              let b' = n
                  s' = s+b'
                  (s'', a') = reduce (s', a)
              in if s''==m then ((a',b'):xs, s''-a', a'+1, b')
                           else (xs, s'', a', b')) ([], 0, 0, 0) [1..m]
    where reduce (s, a) =
              if s>m then reduce (s-a, a+1)
                     else (s, a)
                    
main :: IO ()
main = do
    args <- getArgs
    let n = read (head args)
    putStrLn $ show (orderedPairs n)

Name: Anonymous 2011-04-14 17:46

>>43
how about moe

Name: Anonymous 2011-04-14 18:03

>>28

; in: n = edx, edi = ptr to pairs
; out: edi = # of pairs
    xor eax, eax ; a
    xor ebx, ebx ; b
    xor ecx, ecx ; x
    mov esi, edi
    jmp inloop
nextloop:
    cmp ecx, edx
    jnz notfound
    stosd
    xchg eax, ebx
    stosd
    xchg eax, ebx
notfound:
    cmp ecx, edx
    jb xlessn
    sub ecx, eax
    inc eax
    jmp inloop
xlessn:
    inc ebx
    add ecx, ebx
inloop:
    cmp ebx, edx
    jbe nextloop
    sub edi, esi
    shr edi, 4
    ret

Name: Anonymous 2011-04-14 18:04

>>46
s/shr edi,4/shr edi,3/

Name: Anonymous 2011-04-14 18:07

>>42
Fuck you, I am not bound by the rules of your stupid game.

i like to drnikj sperm from my spermbottle while waring my sperm necklace" - u

FUCK YOU I WON'T DO WHAT YOU TELL ME
FUCK YOU I WON'T DO WHAT YOU TELL ME
FUCK YOU I WON'T DO WHAT YOU TELL ME
FUCK YOU I WON'T DO WHAT YOU TELL ME
FUCK YOU I WON'T DO WHAT YOU TELL ME
FUCK YOU I WON'T DO WHAT YOU TELL ME
FUCK YOU I WON'T DO WHAT YOU TELL ME
FUCK YOU I WON'T DO WHAT YOU TELL ME


fucking fag

Name: Anonymous 2011-04-15 0:36

>>42
There's no reason to be afraid of languages with high-order features. If you can't take lambdas I'm afraid you're a bit of a retard when it comes to being a programmer. (Don't get me wrong, C is great... but only when you need it.)

Name: Anonymous 2011-04-15 1:04

>>49

Suck my dick faggot

Name: Anonymous 2011-04-15 2:37

>>50
Enjoy your toy language, `'faggot'`.

Name: Anonymous 2011-04-15 5:57

http://codepad.org/NVrG8cLJ
bf again, currently there are some overflow bugs. I will work on a better one

Name: Anonymous 2011-04-15 6:56

>>42
My code is pretty fast and portable, it's also better than OPs, so you can fuck off.
A language isn't a toy language, just because it's not popular in the ENTERPRISE.

Name: Anonymous 2011-04-15 13:42

DICENTIS,
 EGO SVM ABELSON ET SVSSMAN,
 PRIMVS ET RELIQVVS,
 CARVS ET CVDDARVS.

Name: Anonymous 2011-04-15 13:44

DICENTIS,
 EGO SVM ABELSON ET SVSSMAN,
 PRIMVS ET RELIQVVS,
 CARVS ET CVDDARVS.

Name: Anonymous 2011-04-15 13:46

DICENTIS,
 EGO SVM ABELSON ET SVSSMAN,
 PRIMVS ET RELIQVVS,
 CARVS ET CVDDARVS.

Name: Anonymous 2011-04-15 13:48

DICENTIS,
 EGO SVM ABELSON ET SVSSMAN,
 PRIMVS ET RELIQVVS,
 CARVS ET CVDDARVS.

Name: Anonymous 2011-04-15 13:49

DICENTIS,
 EGO SVM ABELSON ET SVSSMAN,
 PRIMVS ET RELIQVVS,
 CARVS ET CVDDARVS.

Name: Anonymous 2011-04-16 5:50

my face when this thread

Name: VIPPER 2011-04-16 6:02

>>59
Go die in a JEWS fire.

Name: Anonymous 2011-04-16 11:43

>mfw VIPPER is a huge fucking faggot

Name: Anonymous 2011-04-16 11:51

>>61
>mfw
and add noko to that. Oh my, aren't you a GIGANTIC FAGGOT. back to /b/, kid

Name: Anonymous 2011-04-16 17:03

`>mfw i am told to use noko on an imageboard
fuck you faggot

Name: Anonymous 2011-04-16 17:24

yo guise how do u upload images lol

Name: Anonymous 2011-04-16 17:33

And >>63 is the average imageboarder. The most peculiar characteristic of this subhuman species is the complete lack of any mental skill whatsoever.
As we can see, they refer as themselves as ``i'', and speak a strange language (most likely a subset/dialect of (US) English), composed of words like ``>mfw'', ``>implying'', ``noko'', whose meaning is still unknown.
They seem to be particularly unfriendly, calling everyone a ``faggot'' (or ``fag'', in their language), but in the context of their restricted minds, it may be an act of courtesy. This may justify the complete lack of sage in their posts.
They also seem to have a strange fetish for green-coloured text.

Name: Anonymous 2011-04-16 17:43

>>65
`>implying im from the imageboards
`>mfw your butthurt

Name: Anonymous 2011-04-16 17:49

>>66
Thank you, you too!

Name: Anonymous 2011-04-16 18:49

>>65
>mfw your implying your not a faggot

Name: Anonymous 2011-04-17 2:50

>>68
U MENA FAGGOTFAG

Don't change these.
Name: Email:
Entire Thread Thread List