[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y ] [Search | Free Show | Home]

Can /g/ find all palindromes numbers (reads same forward and

This is a blue board which means that it's for everybody (Safe For Work content only). If you see any adult content, please report it.

Thread replies: 140
Thread images: 20

File: t3_66o6ln[1].jpg (725KB, 2160x3840px) Image search: [Google]
t3_66o6ln[1].jpg
725KB, 2160x3840px
Can /g/ find all palindromes numbers (reads same forward and backwards) under 2 million and sum them?
>>
>>60009208
base 10
>>
>>60009208
16
>>
>>60009215
>>
>>60009172
1000000 * 2000001

All palindrome numbers in base 1 below 2000000. Ez
>>
isn't the trick just to take all the numbers up to 9999 and let the remaining digits be determined by those four?
>>
>>60009172
CL-USER> (loop for x below 2000000 when (string= (write-to-string x) (reverse (write-to-string x))) sum x)
2045041040
>>
Wait
I just realized that's a pc case
Wtf
>>
>>60009239
That's a good start, but consider that not all palindromic numbers have max length, and zeroes are significant, ie. 2, 22, 202, 222, etc. are all palindromic
>>
static void Main(string[] args)
{
List<long> space = new List<long>();
for (int i = 1; i < 2000000; i++)
{
space.Add(i);
}
Console.WriteLine(
space.Where(
o => (o.ToString() == string.Concat(o.ToString().Reverse())) && o > 10
).Sum()
);
}

2045040995
>>
public static void main(String[] args) {
System.out.println(sumPalindromes(2000000));
}

public static int sumPalindromes(int max) {
int sum = 0;
for (int i = 0; i < max; i++) {
String originalNumber = Integer.toString(i);
String reversedNumber = "";

for (int j = originalNumber.length() - 1; j >= 0; j--) {
reversedNumber += originalNumber.charAt(j);
}

if (originalNumber.equals(reversedNumber)) {
sum += i;
}
}
return sum;
}


>2045041040

Remainder that having code maintainability is much more important than having fewer lines of code.
>>
>>60009638
>not developing with TDD and having unit testing
>not adhering to strict OOP principles
>not making interfaces to easily extend functionality
>not having comments
>implying that is maintainable.
>>
>>60009318
Can we consider 20 to be a palindrome by assuming a leading 0 (e.g. 20 == 020)?!?
>>
sumpalindromesundertwomillion();
>>
>>60009809
doEverythin()
>>
>>60009708
>being autistic
>>
>>60009739
Sorry you are being replaced by Rajesh
>>
The sum of all palindromes under some power of 10 has a nice property. Sum of all the palindromes under 100, 10^3, 10^4, 10^5 ,10^6 makes the series
495, 49500, 495000, 49500000, 495000000.
This property should be obvious. The only hard part that requires any work is between 1x10^6-2x10^6. This is simply

 Sum[b 10 ^6 + a 10^5 + c 10^4 + d 10^3 + c 10^2 + a 10 + b, {c, 0, 
9}, {a, 0, 9}, {d, 0, 9}, {b, 1}] [\code]

Summing everything up gives 2045040995
>>
>>60009172
That image makes me wanna get some chilly banana pudding now
>>
>>60009172
So we've got:
2045041040
and
2045040995
Who is correct?
>>
>>60011115
both
>>
>>60011115
The difference is 45 (sum of numbers 1 to 9) Some people ignored single digits.
>>
>>60011115
try it yourslef
>>
c=0
for num in range(10,2*10**6):
if str(num) == str(num)[::-1]:
c+=num
print(c)
[\code]
>>
>>60009739
>20 == 020?!?

Any confirmation of this or should we ignore leading zeroes?
>>
File: 4277814.jpg (224KB, 1000x1000px) Image search: [Google]
4277814.jpg
224KB, 1000x1000px
>>60014997
Bumping for an answer to this.

/g/ still programs, right?
>>

sum(x for x in range(2000001) if str(x) == str(x)[::-1])


>>
>>60016165
python is the only language that can make me cum
>>
(1..2000000).select{|i| i.to_s == i.to_s.reverse}.reduce(&:+)
>>
(defun is-palindrome (num)
(equal (write-to-string num) (reverse (write-to-string num))))

(let ((sum 0))
(loop for x from 1 to 2000000 do (when (is-palindrome x) (incf sum x)))
(format t "Sum of all primes below 2000000 = ~a~%" sum))
>>
File: retard-frog.jpg (24KB, 600x484px) Image search: [Google]
retard-frog.jpg
24KB, 600x484px
>>60016467

>using loop with lisp
>>
>>60016624
Retarded frogposter.
>>
File: 1492441164004.png (400KB, 450x720px) Image search: [Google]
1492441164004.png
400KB, 450x720px
>>60016624
How would you do it?
>>
>>60015851
>>60014997
>>60009739
fuck off retard
>>
>>60016702
It is a legitimate question. Your inability to answer it is sickening.
>>
>>60010785
Should this be
{b, 1, 9}
instead of {b, 1}
no idea what language that is
>>
>>60016731
the fact you are on this board is sickening
literally learn to google you stupid mongoloid
>>
>>60016767
The fact that you exist is sickening.
>>
>>60009172
nope but the world's longest palindromic word is saippuakivikauppias and it means soapstone seller
>>
>>60016677

with reduce and filter ofc
>>
#include <stdio.h>
#include <math.h>
#include <sys/time.h>

#define LIMIT 2000000

int int_pow(int base, int exp) {
int result = 1;
while (exp) {
if (exp & 1)
result *= base;
exp >>= 1;
base *= base;
}

return result;
}

// 123 will return 123321
long long make_palindrome(const int num) {
long long result;
char l = log10(num);
// e.g if num is 123, result becomes 123000
result = num * pow(10, l+1);
char i;
for (i = 1; i <= l+1; ++i) {
result += ( (num % int_pow(10, i)) / int_pow(10, i-1) ) *
int_pow(10, l-i+1);
}
return result;
}

// 123, 4 will return 1234321
long long make_palindrome_with_mid(const int num, const int mid) {
long long result;
char l = log10(num);
// e.g if num is 123, result becomes 1230000
// space for mid num ^
result = num * pow(10, l+1+1);
// Puts in mid number
result += mid * pow(10, l+1);
char i;
for (i = 1; i <= l+1; ++i) {
result += ( (num % int_pow(10, i)) / int_pow(10, i-1) )
* int_pow(10, l-i+1);
}
return result;
}

int main(void) {
struct timeval start, end;

long long sum = 45; // Sum of numbers 1-9
// Largest palindrome under 2000000 is 1999991 which is 199 with 9
// in the middle so the loop only has to go up to 199.
int i, j;
for (i = 1; i <= 199; ++i) {
sum += make_palindrome(i);
for (int j = 0; j <= 9; ++j) {
sum += make_palindrome_with_mid(i, j);
}
}
printf("%lli\n", sum);
return 0;
}


got 1565040640, works very fast chumps
>>
>>60017287
way off
see >>60011115 and >>60011824 and >>60010785
>>
>>60017511
Fixed the main function, now it gives the correct answer 2045041040
I skipped all the numbers which begin with 200-999 eg 200002
int main(void) {
struct timeval start, end;

long long sum = 45; // Sum of numbers 1-9
// Largest palindrome under 2000000 is 1999991 which is 199 with 9
// in the middle so the loop only has to go up to 199.
int i, j;
long long temp;
for (i = 1; i <= 999; ++i) {
temp = make_palindrome(i);
sum += temp;
if (i <= 199) {
for (int j = 0; j <= 9; ++j) {
temp = make_palindrome_with_mid(i, j);
sum += temp;
}
}
}
printf("%lli\n", sum);
return 0;
}
>>
>>60016735
No b must be less than 2 as it's the "millions". It's Mathematica. It's the sum for the 1-2 million palindromes.
>>
>>60009172
>>60009281
>>60016833
IS IT A COINCIDENCE YOU POSTED A RACECAR BECAUSE RACECAR IS A PALINDROME
>>
>>60017287
#include <stdio.h>

typedef struct { char length; char digits[7]; } digits;

digits getDecimalDigits(unsigned long value) {
digits extractedDigits = {0, {0, 0, 0, 0, 0, 0, 0}};
while (value) {
extractedDigits.digits[extractedDigits.length] = value % 10;
extractedDigits.length++;
value = value / 10;
}
return extractedDigits;
}

char digitsArePalindrome(digits theDigits) {
char left = 0;
char right = theDigits.length - 1;
if (theDigits.length) {
while (right > left) {
if (theDigits.digits[left] != theDigits.digits[right]) {
return 0; }
left += 1; right -= 1;
}
return 1;
}
return 0;
}

int main(int argc, const char * argv[]) {
digits tempDigits;
unsigned long total = 0;
for (unsigned long i = 1; i < 2000000; i++) {
tempDigits = getDecimalDigits(i);
if (digitsArePalindrome(tempDigits)) { //printf("palindrome: %lu\n", i);
total += i; }
}
printf("Sum of all palindromes numbers under 2 million: %lu\n", total);
return 0;
}


Sum of all palindromes numbers under 2 million: 2045041040
>>
File: JEB_BUSH.png (246KB, 353x396px) Image search: [Google]
JEB_BUSH.png
246KB, 353x396px
>>60017804
mine is faster lulz
>>
>>60010785
>
Sum[b 10 ^6 + a 10^5 + c 10^4 + d 10^3 + c 10^2 + a 10 + b, {c, 0, 
9}, {a, 0, 9}, {d, 0, 9}, {b, 1}]

Can someone please break down this equation / explain it in english?
>>
>>60017892
Yeah just wait a few minutes.
>>
>>60017889
>Optimizing non-critical sections.
I respect the attitude but is a huge time-waster for little benefit.
>>
> sum [ x | x <- [1..2000000], show x == reverse (show x) ]
2045041040
>>
>>60017892
It's generating the palindromes of the form
bacdcab
and adding them up, where 0 <= a,c,d <= 9. I don't know Mathematica so I don't know if b = 1 or 0 <= b <= 1.
I don't think its correct though, because that will only work for 7 digit palindromes, not for 6,5,4,3,2,1 digit palindromes.
>>
>>60010785
>The only hard part that requires any work is between 1x10^6-2x10^6
Sum of all palindrome numbers between 100 and 200: 1460
Sum of all palindrome numbers between 1000 and 2000: 14960
Sum of all palindrome numbers between 10000 and 20000: 1499600
Sum of all palindrome numbers between 100000 and 200000: 14999600
Sum of all palindrome numbers between 1000000 and 2000000: 1499996000

What is the formula?
>>
>>60017645
OP here, I didn't even realize this when I made the thread
>>
>>60018077
Bumping in hopes that someone can figure out the formula for the sum of all palindrome numbers between 10^x and 2 * 10^x.
>>
>>60009208
Base cocaine
>>
>>60009234
literally not how arabic numerals work
>>
>>60009172
in ruby:
(1..2_000_000).select{|e| e.to_s == e.to_s.reverse}.sum
>>
>>60019116
>2_000_000
Disgusting.
>>
>>60019157
Why? for constant numbers it makes it easier to read
>>
>>60019214
The human eye can parse... 9 zeros


ARE YOU NOT HUMAN!?!!? WHAT ARE YOU?????
>>
Java 8 Bitches!
import java.util.stream.LongStream;
public class App {
public static void main(String[] args) {
System.out.println(new App().sumUpTill(2000000L));
}

long sumUpTill(Long arg) {
return LongStream.range(1, arg)
.filter(this::isP)
.sum();
}

boolean isP(Long l){
String str = l.toString();
return str.equals(new StringBuilder(str).reverse().toString());
}
}
>>
>>60019241
yep because fuck readability amirite? if it saves one person on your team from misreading the constant (and subsequently fucking up somewhere else) it's totally not worth it
>>
>>60019258

>new App()
dude what
>>
>>60019329
method references in streams don't work in a static context.

It could be rewritten without the static reference like this:
import java.util.stream.LongStream;

public class App {
public static void main(String[] args) {
System.out.println(sumUpTill(2000000L));
}

static long sumUpTill(Long arg) {
return LongStream.range(1, arg)
.filter(l -> isP(l))
.sum();
}

static boolean isP(Long l){
String str = l.toString();
return str.equals(new StringBuilder(str).reverse().toString());
}
}
>>
>>60019323
>Having people on your team whose eyes are incapable of accurately parsing 9 zeroes...

No wonder most software these days has huge problems.
>>
>>60019323
NINE ZEROS
>>
>>60019386
most software these days is developed in spaces where hiring managers are rubbing the backs of 30 year old wannabes playing xbox at work and talking to the news about work life balance when asked to work overtime to complete a project on time
>>
>>60019386
This isn't even worth arguing with. The end result is the same, but using the 2_000 notation is more readable, there is no denying that.
So why not use it other than to feel better than everyone like you are so demonstrating here?
>>
>>60019362

Or just do this
import java.util.stream.LongStream;
public class App {
public static void main(String[] args) {
System.out.println(sumUpTill(2000000L));
}

private static long sumUpTill(Long arg) {
return LongStream.range(1, arg)
.filter(App::isP)
.sum();
}

private static boolean isP(Long l){
String str = l.toString();
return str.equals(new StringBuilder(str).reverse().toString());
}
}

This looks ugly as fuck, functional programming does not belong in Java.
>>
>>60017937
>
sum [ x | x <- [1..2000000], show x == reverse (show x) ]

SyntaxError: invalid syntax
>>
>>60019540
Good going, pythonista.
>>
>>60019560
Your post is invalid.
>>60019418
>Arguing in favor of having incompetent members in your team
Your argument is invalid.
>>
>>60019592
That was Haskell code you dumbass.
>>
>>60016165
Disgustingly slow
>>
>>60019610
>Disgust at people not optimizing non-critical sections
Disgustingly sub-optimal in the time-dimension
>>
>>60019459
I disagree, its so nice to have FP in Java. It makes collection processing so much quicker thanks to parallelStream(). Automatic true Fork/Join multithreading for free!

Also the fact that java.util.Logging uses supplier concepts now it saves a lot of string concatenation unless its actually supposed to log. Good stuff all around.

>>60019592
I'm not saying they're incompetent, the fact of the matter is that people make mistakes. Using the 2_000 notation lowers the chance of making a mistake, it doesn't mean that they're fucking incompetent. Christ this is getting ridiculous.
Going by your logic we should all code without comments because who needs comments unless you're incompetent!

>>60019607
/g/ in a nutshell
>>
>>60019649
how do you know the disgust was aimed at the programmer and not the high-level and inefficient abstractions they used?
>>
>>60019649
Run that code and come back to me tomorrow when it finishes
>>
>>60019607
>Using Haskell
>Calling other people dumbass

ugh...
>>
>>60019676
I didn't write it, ya big dum dum.
>>
>>60019664

It seems useful to have, but what the hell is with the ::? I thought we left that mess behind with C++.
>>
>>60019664
2000000000
2_000_000_000

and most people would still have to look twice for billion or million

people are fucking idiots, get over it. just because we're able to overcome our stupidity to smash atoms means nothing yet
>>
>>60019690
Oh yeah I agree with you there, :: is a terrible notation for a method reference. C++ begone!
>>
>>60019674
1.3 seconds runtime.

Given the question we are trying to answer it would be a sickening waste of our time to try to construct any kind of elaborate, generic, or abstract solution. (simple solution: few minutes to conceive, 1.3 seconds runtime; complex solution: 15+ minutes to conceive and type, 0.5 seconds runtime)
>>
>>60019697
You have yet to invalidate the argument that it is disgustingly inefficient to have incompetent people on your team whose eyes can't even parse 9-12 zeroes.
>>
CS major answer
>Make a 2 million loop
>make a reverse function
>check if current number equals reversed
>add number to a sum
>>
>>60019778
Not the guy you're arguing with, but not everyone is a 10x-er like everyone here on /g/ (loljk). So I think his point is valid.

In the corporate world (or any job with a team bigger than like 5 people really) readability is more important than everything else, and the underscore notation does improve that.
>>
>>60019778
no no no, i cant. people who can't figure our figures are a cancer
>>
>>60019747
Time to run the code in >>60017804 :
0.255411s
>>
>>60019747
>>60019873
Python confirmed 6.5 times slower than C
>>
File: scrot.png (68KB, 859x490px) Image search: [Google]
scrot.png
68KB, 859x490px
>>60019873
lets throw the java version in here too!
>>
File: pp.jpg (73KB, 300x250px) Image search: [Google]
pp.jpg
73KB, 300x250px
>>60019805
>>
>>60019909
Nice. Post specs.
>>
>>60019909
:: is valid Java syntax when?
>>
>>60019805
My initial thought was this. It makes me feel sad and brainlet
>>
File: scrot2.png (86KB, 861x550px) Image search: [Google]
scrot2.png
86KB, 861x550px
When the JVM gets nice and warmed up and JITs it its even faster!

>>60019920
Xeon E3-1231v3 + 16gb ddr3! haha
>>60019923
Java 8, method references and Functional Programming = <3
>>
File: 2919689-4831166425-29196.gif (1MB, 195x229px) Image search: [Google]
2919689-4831166425-29196.gif
1MB, 195x229px
>>60019950
hmm some of that new functional stuff sounds pretty intense
>>
>>60019948
Why?
>>
>>60019974
Cuz I literally used 1% of my brain to think about this solution. It's literally high school tier.
>>
>>60019873
System: i7-3615QM CPU @ 2.30GHz (pretty sure turbo is disabled on my system)
>>60019950
@ 3.40 GHz (Turbo @ 3.80 GHz)
>>
>>60019909
How is the JVM working here? Is it interpreting / translating to machine code?
>>
>>60020019
Oh yeah for sure, heres how that code runs on my system:
 /tmp $ gcc test.c 
/tmp $ ./a.out
Sum of all palindromes numbers under 2 million: 2045041040
/tmp $ time ./a.out
Sum of all palindromes numbers under 2 million: 2045041040

real 0m0.075s
user 0m0.073s
sys 0m0.000s
/tmp $

75ms! 50% faster than the jvm version still!
>>
>>60020067
The jvm interprets it the first time, then it JITs it once, then it JITs it again for the final product. You can see it in the times on the side: ~213ms -> ~150ms -> ~125ms
>>
>>60019896
I'm sure if it was implemented in python the same way it would have a faster runtime.
>>
File: fastboiii.png (31KB, 735x86px) Image search: [Google]
fastboiii.png
31KB, 735x86px
the full fixed code
#include <stdio.h>
#include <math.h>
#include <time.h>

int int_pow(int base, int exp) {
int result = 1;
while (exp) {
if (exp & 1)
result *= base;
exp >>= 1;
base *= base;
}

return result;
}

// 123 will return 123321
long long make_palindrome(const int num) {
long long result;
char l = log10(num);
// e.g if num is 123, result becomes 123000
result = num * pow(10, l+1);
char i;
for (i = 1; i <= l+1; ++i) {
result += ( (num % int_pow(10, i)) / int_pow(10, i-1) ) *
int_pow(10, l-i+1);
}
return result;
}

// 123, 4 will return 1234321
long long make_palindrome_with_mid(const int num, const int mid) {
long long result;
char l = log10(num);
// e.g if num is 123, result becomes 1230000
// space for mid num ^
result = num * pow(10, l+1+1);
// Puts in mid number
result += mid * pow(10, l+1);
char i;
for (i = 1; i <= l+1; ++i) {
result += ( (num % int_pow(10, i)) / int_pow(10, i-1) )
* int_pow(10, l-i+1);
}
return result;
}

int main(int argc, char** argv) {
clock_t start, end;

start = clock();
long long sum = 45; // Sum of numbers 1-9
// Largest palindrome under 2000000 is 1999991 which is 199 with 9
// in the middle so the loop for palindromes with mid numbers
// only has to go up to 199.
int i, j;
long long temp;

for (i = 1; i <= 999; ++i) {
temp = make_palindrome(i);
sum += temp;
if (i <= 199) {
for (int j = 0; j <= 9; ++j) {
temp = make_palindrome_with_mid(i, j);
sum += temp;
}
}
}
end = clock();
printf("%lli\n", sum);
printf("Took %f seconds\n", (double)(end - start) / CLOCKS_PER_SEC);
return 0;
}
>>
>>60020129
oh god yeah I forgot to compile with optimizations! Down to 17ms with that!
>>
File: evenfaster.png (13KB, 472x44px) Image search: [Google]
evenfaster.png
13KB, 472x44px
i forgot to replace the uses of pow with int_pow and now its a bit faster
>>
>>60020129
>the sum isn't a palindrome
Is there a good way to find palindromes which are sums of other palindromes?
>>
>>60020336
we need to go deeper!
>>
>>60020336
you could build a bool array to act as palindrome flags like a sieve of erathosthenes and then do loads of sums with that and check said sums to be palindromes
>>
>>60020093
It is actually much slower

Code in palindromes.py:
def getDecimalDigits(value):
extractedDigits = [0, [0, 0, 0, 0, 0, 0, 0]]
while (value):
extractedDigits[1][extractedDigits[0]] = value % 10
extractedDigits[0] += 1
value = value // 10
return extractedDigits


def digitsArePalindrome(theDigits):
left = 0
right = theDigits[0] - 1
if (theDigits[0]):
while (right > left):
if (theDigits[1][left] != theDigits[1][right]):
return 0
left += 1
right -= 1
return 1
return 0

def palindromeMain():
tempDigits = getDecimalDigits(0)
total = 0
min = 0
max = 2000000
current = min
while (current < max):
tempDigits = getDecimalDigits(current)
if (digitsArePalindrome(tempDigits)):
total += current
current += 1
print(total)

if (__name__ == "__main__"):
palindromeMain()

Runtime: 0m8.018s
>>
File: scrot3.png (225KB, 1265x1059px) Image search: [Google]
scrot3.png
225KB, 1265x1059px
>>60019950
Alrighty final Java 8 runtimes. Made a graph showing how the JVM handles stuff like this too.
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

import com.google.common.io.Files;

/**
* Sum up all the numbers from 1 - 2 Million using Function Programming Concepts
*/
public class App {
public static void main(String[] args) {
List<Integer> results = new ArrayList<>();
for (int i = 0; i < 50; i++) {
Instant start = Instant.now();
System.out.println(sumUpTill(2_000_000L));
Instant end = Instant.now();

results.add((int) Duration.between(start, end).toMillis());

System.out.println("Took: " + Duration.between(start, end).toMillis() + "ms\n");
}

System.out.println(
"Average: " + results.stream().reduce(0, (x, y) -> x + y) / results.size() + "ms");

AtomicInteger count = new AtomicInteger(0);
List<String> csvOutput = results.stream().map(x -> {
return count.getAndIncrement() + "," + x.toString();
}).collect(Collectors.toList());

try {
Files.write(String.join("\n", csvOutput), new File("/tmp/out.csv"),
StandardCharsets.UTF_8);
}
catch (IOException e) {
// lol
}
}

protected static long sumUpTill(Long arg) {
return LongStream.range(1, arg).filter(App::isPalindrome).sum();
}

private static boolean isPalindrome(Long l) {
String str = l.toString();
return str.equals(new StringBuilder(str).reverse().toString());
}
}

>>
>>60020423
8 seconds....ouch thats sad
>>
File: haskell.png (786KB, 1000x1300px) Image search: [Google]
haskell.png
786KB, 1000x1300px
palindrome :: Int -> Int
palindrome 10 = 0
palindrome n = if reverse (show n) == show n
then palindrome (n-1) + n
else palindrome (n-1)
main = do
print $ palindrome 2000000
>>
>>60020129
>
long long sum = 45; // Sum of numbers 1-9

May as well start with

long long sum = 2045041040; // Sum of palindromes between 1 and 2000000


Anyway. Output on my system:
2045041040
Took 0.000566 seconds

real 0m0.004s
user 0m0.002s
sys 0m0.002s
>>
>>60009172
LIMIT = 2000000

def is_palindrome(number):
numb_str = str(number)
reversed = numb_str[::-1]

if numb_str.__eq__(reversed):
return True
else:
return False

sum = 45 # sum of the first 10 numbers
for i in range(10, 2000000):
if is_palindrome(i):
sum += sum
print(sum)

>>
>>60020726
1.6 seconds runtime, also
>
sum += sum

should be
sum += i
>>
>>60020067
see
>>60020570
for visualization
>>
>>60020774
Okay it's fixed
Also it's looping through 2,000,000 numbers how can you expect that to be fast?
>>
>>60020706
unoptimized
#include <unistd.h>

const char *text = "2045041040\n";

int main (void) {
write (1, text, 11);
return 0;
}
>>
>>60021160
I fixed it to handle errors because I am not a code monkey.

#include <unistd.h>

int main (void) {
return (write (1, "2045041040\n", 11) == -1);
}
>>
>>60020726
if numb_str.__eq__(reversed):
return True
else:
return False


Why wouldn't you just do ...

return numb_str == reversed
>>
File: DEEP.png (29KB, 685x86px) Image search: [Google]
DEEP.png
29KB, 685x86px
DEEPER
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <time.h>

int int_pow(int base, int exp) {
int result = 1;
while (exp) {
if (exp & 1)
result *= base;
exp >>= 1;
base *= base;
}

return result;
}

long long make_palindrome(const int num) {
long long result;
char l = log10(num);
result = num * int_pow(10, l+1);
char i;
for (i = 1; i <= l+1; ++i) {
result += ( (num % int_pow(10, i)) / int_pow(10, i-1) ) *
int_pow(10, l-i+1);
}
return result;
}

long long make_palindrome_with_mid(const int num, const int mid) {
long long result;
char l = log10(num);
result = num * int_pow(10, l+1+1);
result += mid * int_pow(10, l+1);
char i;
for (i = 1; i <= l+1; ++i) {
result += ( (num % int_pow(10, i)) / int_pow(10, i-1) )
* int_pow(10, l-i+1);
}
return result;
}

char is_palindrome(const long long num) {
char i, l = log10(num);
for (i = 1; i <= l+1; ++i) {
if ((num % int_pow(10, i)) / int_pow(10, i-1) !=
(num % int_pow(10, l-i+2)) / int_pow(10, l-i+1))
{
return 0;
}
}
return 1;
}

int main(int argc, char** argv) {
clock_t start, end;

start = clock();
long long sum = 45; // Sum of numbers 1-9
int i, j;
long long temp;
char palindromes[2000001];
memset(palindromes, 0, 2000001);
memset(palindromes, 1, 10);
size_t s;

for (i = 1; i <= 999; ++i) {
palindromes[make_palindrome(i)] = 1;
if (i <= 199) {
for (int j = 0; j <= 9; ++j) {
palindromes[make_palindrome_with_mid(i, j)] = 1;
}
}
}

for (i = 0; i <= 2000000; ++i) {
if (!palindromes[i])
continue;

for (j = 0; j <= 2000000; ++j) {
if (!palindromes[j])
continue;

temp = i+j;
if (is_palindrome(temp))
sum += temp;
}
}

end = clock();
printf("The sum to all the palindrome sums of two palindromes"
" under 2000000 is %lli\n",sum);
printf("Took %f seconds\n", (double)(end - start) / CLOCKS_PER_SEC);
return 0;
}

had to omit some comments
>>
>>60010618
top kek
the one time that phrase will be a good thing
>>
>>60021294
it keeps getting slower!
>>
>>60021410
its a big calculation
>>
>>60020883
Even the JVM can get within 2* the C code (0.1 seconds).

Pretty sad to see how slow python is.
>>
Don't you just have to count up, mirror the number and append that number and watch that it's lower than two million to find all palindromes?
>>
>>60009172
Now find the sum of numbers which are palindromic in both base 10 and base 2.
>>
Declare sum = 0
For loop
Convert integer (or big Int if you need to) to string
Reverse string, if matches original, add int to sum
>>
>>60021632
static void Main(string[] args)
{
List<int> space = new List<int>();
for (int i = 1; i < 2000000; i++)
{
space.Add(i);
}
var s = space.Where(k => k == Convert.ToInt32(new string(Convert.ToString(k, 2).Reverse().ToArray()), 2) && k > 1).ToList();
Console.WriteLine(
space.Where(
o => (o.ToString() == string.Concat(o.ToString().Reverse())) && o > 10
).Where(o => s.ToList().Contains(o)).Select(o => (long)o).Sum()
);
}


I get 6544915
>>
>>60018077
Bump give me some time and I'll work it out.
>>60018066
It's for the sum of all palindromes in a range 1-2 mil
>>
>>60024360
>Bump give me some time and I'll work it out.
bumping waiting for this.
>>
>>60025530
Bumping this.
>>
sum(i for i in xrange(2000000) if str(i) == reverse(str(i)))
>>
>>60026436
Final bump.
>>
Alright

For palindromes in a range 10^n-1 - 10^n, where n is odd, we have the formula

 99 2^(3/2 (-1 + n)) 5^(-(1/2) + (3 n)/2) 


This is from observing that for an odd n the total can be written as

((10^((1/2 (n + 1)) - 1)) *45 *(1 + 10^n)) + 
9 *(10^((1/2 (n + 1)) - 2))* 45 *
\sum_{k=1}^{(n+1)/2-1} (10^(n - k) + 10^k)

this is just by noticing anything can be written as

\sum_{a_1} \sum_{a_2} .... ( a_1( 10^n + 1) + a_2 (10^n-1 + 10^1) + .....)

where you sum over a_1 from 1->9 while a_i are from 0-9

For even powers of n you have a single "10^n/2" term in the middle so its slightly different

 99 2^(-2 + (3 n)/2) 5^(-1 + (3 n)/2) 


This was from a modification of the odd sum to account for this

[code ] ((10^((1/2 (n)) - 1)) *45 *(1 + 10^n)) +
9 *(10^((1/2 (n)) - 2))*
45 *(10^(n/2) + \sum_{k=1}^{ n/2-1} (10^(n - k) + 10^k ))

Now for numbers in 1x10^(n-1) - > 2 x 10^(n)
where n is odd, we just need to modify our results slightly

((10^((1/2 (n + 1)) - 1)) *1 *(1 + 10^n)) + (10^((1/2 (n + 1)) - 2))*
45 * \sum_{k=1}^{(n+1)/2} (10^(n - k) + 10^k) )

as the outer sum for a_1 is replaced by a constant 1. This sum reduces to

 2^(1/2 (-3 + n)) 5^(1/2 (-1 + n)) (-8 + 3 10^n) 


The even case is left as an exercise to the reader.
>>
>>60028015
Looks like I forgot some code tags, oh well, still readable
>>
>>60028015
>For palindromes in a range 10^n-1 - 10^n, where n is odd, we have the formula

This should be 10^n - 10^n+1
Thread posts: 140
Thread images: 20


[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y] [Search | Top | Home]

I'm aware that Imgur.com will stop allowing adult images since 15th of May. I'm taking actions to backup as much data as possible.
Read more on this topic here - https://archived.moe/talk/thread/1694/


If you need a post removed click on it's [Report] button and follow the instruction.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com.
If you like this website please support us by donating with Bitcoins at 16mKtbZiwW52BLkibtCr8jUg2KVUMTxVQ5
All trademarks and copyrights on this page are owned by their respective parties.
Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
This is a 4chan archive - all of the content originated from that site.
This means that RandomArchive shows their content, archived.
If you need information for a Poster - contact them.