• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 01:50
CEST 07:50
KST 14:50
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
[ASL20] Ro16 Preview Pt1: Ascent8Maestros of the Game: Week 1/Play-in Preview12[ASL20] Ro24 Preview Pt2: Take-Off7[ASL20] Ro24 Preview Pt1: Runway132v2 & SC: Evo Complete: Weekend Double Feature4
Community News
LiuLi Cup - September 2025 Tournaments2Weekly Cups (August 25-31): Clem's Last Straw?39Weekly Cups (Aug 18-24): herO dethrones MaxPax6Maestros of The Game—$20k event w/ live finals in Paris64Weekly Cups (Aug 11-17): MaxPax triples again!15
StarCraft 2
General
Weekly Cups (Sept 1-7): MaxPax rebounds & Clem saga continues Production Quality - Maestros of the Game Vs RSL 2 #1: Maru - Greatest Players of All Time Team Liquid Map Contest #21 - Presented by Monster Energy Geoff 'iNcontroL' Robinson has passed away
Tourneys
Maestros of The Game—$20k event w/ live finals in Paris Sparkling Tuna Cup - Weekly Open Tournament RSL: Revival, a new crowdfunded tournament series Chzzk MurlocKing SC1 vs SC2 Cup Sea Duckling Open (Global, Bronze-Diamond)
Strategy
Custom Maps
External Content
Mutation # 490 Masters of Midnight Mutation # 489 Bannable Offense Mutation # 488 What Goes Around Mutation # 487 Think Fast
Brood War
General
Exploring the Bold World of Mike Tyson Vape Flavor ASL20 General Discussion BSL Polish World Championship 2025 20-21 September [ASL20] Ro16 Preview Pt1: Ascent BGH Auto Balance -> http://bghmmr.eu/
Tourneys
[ASL20] Ro16 Group A [IPSL] ISPL Season 1 Winter Qualis and Info! [Megathread] Daily Proleagues Is there English video for group selection for ASL
Strategy
Simple Questions, Simple Answers Muta micro map competition Fighting Spirit mining rates [G] Mineral Boosting
Other Games
General Games
Stormgate/Frost Giant Megathread General RTS Discussion Thread Nintendo Switch Thread Path of Exile Warcraft III: The Frozen Throne
Dota 2
Official 'what is Dota anymore' discussion
League of Legends
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread Vanilla Mini Mafia
Community
General
US Politics Mega-thread The Games Industry And ATVI Things Aren’t Peaceful in Palestine UK Politics Mega-thread Russo-Ukrainian War Thread
Fan Clubs
The Happy Fan Club!
Media & Entertainment
[Manga] One Piece Anime Discussion Thread Movie Discussion! [\m/] Heavy Metal Thread
Sports
Formula 1 Discussion MLB/Baseball 2023 2024 - 2026 Football Thread TeamLiquid Health and Fitness Initiative For 2023
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread High temperatures on bridge(s)
TL Community
The Automated Ban List TeamLiquid Team Shirt On Sale
Blogs
Collective Intelligence: Tea…
TrAiDoS
A very expensive lesson on ma…
Garnet
hello world
radishsoup
Lemme tell you a thing o…
JoinTheRain
RTS Design in Hypercoven
a11
Evil Gacha Games and the…
ffswowsucks
INDEPENDIENTE LA CTM
XenOsky
Customize Sidebar...

Website Feedback

Closed Threads



Active: 1206 users

Project Euler, Problem 14.

Blogs > Adeny
Post a Reply
Normal
Adeny
Profile Blog Joined January 2009
Norway1233 Posts
November 04 2009 19:12 GMT
#1
Yo, so I started project euler a couple days ago, and some of the problems are pretty challenging already, for someone who's only had 10 grades of math. I've done quite a bit of googling, compared some codes and whatnot, but i never found a c++ example, and it's the only language i'm somewhat familiar with, so other's solutions are hard to understand. I know that asking for help on a project euler problem is pretty lame, but i'm completely stuck and very curious as to what i'm doing wrong. Not really the right place to ask either, but I don't know where else would be more appropriate, so here we go:

The problem:
+ Show Spoiler +

The following iterative sequence is defined for the set of positive integers:

n → n/2 (n is even)
n → 3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

NOTE: Once the chain starts the terms are allowed to go above one million.


I've checked and double-checked my solution many times but I can't for the life of me see how it's wrong, here's the code: (Pretty sloppy but w/e, it's short)

+ Show Spoiler +

#include <iostream>
#include <windows.h>
#include "conio.h"

using namespace std;

int temp = 0; // temp stores chain length
int maxnum = 0; // max chain
int begnum = 0; // max beginning number
int tempbegnum = 0; // temp max beginning number
void sequence(int n)
{
temp = 0;
tempbegnum = n;
while (n > 1)
{
if (n % 2 == 0)
{
n = n/2;
}
else
{
n = n*3+1;
}
temp++;
}
if (temp > maxnum && n == 1)
{
maxnum = temp;
begnum = tempbegnum;
}

return;
}


int main()
{

for (int i = 0; i < 1000000; i++)
{
sequence(i);
}
cout << maxnum << endl << begnum;

_getch();
return 0;
}


*
Kau *
Profile Joined March 2007
Canada3500 Posts
November 04 2009 19:23 GMT
#2
I just skimmed your code so this question might be useless, but what happens if several chains have the same chain length? Do you take the smallest number or the largest?
Moderator
Adeny
Profile Blog Joined January 2009
Norway1233 Posts
November 04 2009 19:24 GMT
#3
I didn't really think of it because I assumed one definite answer, but only if the current chain is OVER the max chain will it be stored.
CTStalker
Profile Blog Joined November 2004
Canada9720 Posts
November 04 2009 19:30 GMT
#4
don't have the time now to help out, but a general tip: if you want people to read your code, some indenting will help.
By the way, my name is Funk. I am not of your world
Adeny
Profile Blog Joined January 2009
Norway1233 Posts
November 04 2009 19:31 GMT
#5
I'm sorry that would be the forum's fault. Don't know how to fix it.
CTStalker
Profile Blog Joined November 2004
Canada9720 Posts
November 04 2009 19:32 GMT
#6
oh. right.

my bad
By the way, my name is Funk. I am not of your world
CTStalker
Profile Blog Joined November 2004
Canada9720 Posts
November 04 2009 19:40 GMT
#7

#include <iostream>
#include <windows.h>
#include "conio.h"

using namespace std;

int temp = 0; // temp stores chain length
int maxnum = 0; // max chain
int begnum = 0; // max beginning number
int tempbegnum = 0; // temp max beginning number
void sequence(int n)
{
temp = 0;
tempbegnum = n;
while (n > 1)
{
if (n % 2 == 0)
{
n = n/2;
}
else
{
n = n*3+1;
}
temp++;
}

if (temp > maxnum && n == 1)
{
maxnum = temp;
begnum = tempbegnum;
}

return;
}


int main()
{

for (int i = 0; i < 1000000; i++)
{
sequence(i);
}
cout << maxnum << endl << begnum;

_getch();
return 0;
}
By the way, my name is Funk. I am not of your world
Adeny
Profile Blog Joined January 2009
Norway1233 Posts
November 04 2009 19:42 GMT
#8
Sick, how'd you do that? For future reference.
Insane
Profile Blog Joined November 2003
United States4991 Posts
Last Edited: 2009-11-04 20:01:47
November 04 2009 19:52 GMT
#9
With the [code] tag
You could hit quote and it shows you what he used to make his post.


Without actually writing code or solving the problem: are you sure you are not overflowing int?
category
Profile Joined July 2009
United States85 Posts
November 04 2009 19:53 GMT
#10
Project Euler is badass. Good for you for taking on the challenge. You will learn a lot in the process.
Navane
Profile Blog Joined February 2007
Netherlands2748 Posts
November 04 2009 20:00 GMT
#11
it counts one to many. But since it does it with al of the numbers, the number with the most is still the number with the most. But the array is one number shorter.

(i tested it with i < 5, it says 7 / 3, meaning array(3) has seven items, which is untrue: 3 10 5 16 8 4 2 1)
Insane
Profile Blog Joined November 2003
United States4991 Posts
Last Edited: 2009-11-04 20:12:06
November 04 2009 20:09 GMT
#12
OK, I did it in C# using a similar method to yours and it works fine using a long instead of an int. (I don't mean for the chain length--I mean for the value that you actually change to n/2 or 3n+1)

On November 05 2009 05:00 Navane wrote:
it counts one to many. But since it does it with al of the numbers, the number with the most is still the number with the most. But the array is one number shorter.

(i tested it with i < 5, it says 7 / 3, meaning array(3) has seven items, which is untrue: 3 10 5 16 8 4 2 1)

I don't really understand what you're trying to communicate with this post. He never uses an array...?


e: In case it's not clear, I never ran your code
This was my C# solution. And no I don't write actual ugly code like the for statement in production :D

+ Show Spoiler +
        static void Main(string[] args)
{
int longest = 0;
int longestIndex = 1;
for (int i = 1; i < 1000000; i++)
{
int temp = ChainLength(i);
if (temp > longest)
{
longestIndex = i;
longest = temp;
}
}
Console.WriteLine(string.Format("{0}: {1}", longestIndex, longest));
Console.Read();
}

private static int ChainLength(long a)
{
int c;
for (c = 0; a != 1; c++, a = (a % 2 == 0) ? a / 2 : (3 * a) + 1) ;
return c;
}
Adeny
Profile Blog Joined January 2009
Norway1233 Posts
Last Edited: 2009-11-04 20:12:49
November 04 2009 20:11 GMT
#13
OK, I did it in C# using a similar method to yours and it works fine using a long instead of an int. (I don't mean for the chain length--I mean for the value that you actually change to n/2 or 3n+1)


I don't even know what to say to this... I'm so bad.
Atleast I got it solved, right? ONWARDS!
Insane
Profile Blog Joined November 2003
United States4991 Posts
Last Edited: 2009-11-04 20:13:28
November 04 2009 20:13 GMT
#14
On November 05 2009 05:11 Adeny wrote:
Show nested quote +
OK, I did it in C# using a similar method to yours and it works fine using a long instead of an int. (I don't mean for the chain length--I mean for the value that you actually change to n/2 or 3n+1)


I don't even know what to say to this... I'm so bad.

You mean you don't know what to say that you missed that, or you don't know what I mean?
e: nevermind, you edited your post so it's clear what you mean
Thratur
Profile Blog Joined June 2008
Canada917 Posts
November 04 2009 20:36 GMT
#15
How do you know it's wrong?
AssuredVacancy
Profile Blog Joined September 2008
United States1167 Posts
November 04 2009 20:36 GMT
#16
I'm thinking a way to optimize it would be have an array to store the results of lower numbers of how long before the chain terminates. AKA, if you did sequence(13), and found that it takes 10 steps before it ends, you store 10 at array index 13, so the NEXT time a bigger number arrives at 13, you know that it's gonna end in 10 steps so you don't have to waste time calculating the rest. Do it recursively and it should be wayyyy faster.
We spend our youth attaining wealth, and our wealth attaining youth.
searcher
Profile Blog Joined May 2009
277 Posts
November 04 2009 20:36 GMT
#17
If you want to learn even more about this:
Collatz Conjecture
Adeny
Profile Blog Joined January 2009
Norway1233 Posts
November 04 2009 20:53 GMT
#18
On November 05 2009 05:36 AssuredVacancy wrote:
I'm thinking a way to optimize it would be have an array to store the results of lower numbers of how long before the chain terminates. AKA, if you did sequence(13), and found that it takes 10 steps before it ends, you store 10 at array index 13, so the NEXT time a bigger number arrives at 13, you know that it's gonna end in 10 steps so you don't have to waste time calculating the rest. Do it recursively and it should be wayyyy faster.


Interesting, but execution time is near-immediate on this, and I'm not good enough to think about optimalizations yet, it's challenging enough just to come up with the right answer, as you've seen.
Also I noticed now that when my program didn't work with the beginning value set to zero i changed the if (tempstring > maxstring) or whatever to if (tempstring > maxstring && n == 1), which is obviously very stupid as that gets checked every loop, right after while (n > 1), completely unecessary. I don't know where my mind whas at when I decided upon that instead of just changing it to start counting from 3 or something.
iSiN
Profile Blog Joined March 2009
United States1075 Posts
November 04 2009 20:54 GMT
#19
you program with C# peter...this makes me sad
Grouty @HoN/PCKJ <--<333 || Jaedong Fan Cafe GFX
Insane
Profile Blog Joined November 2003
United States4991 Posts
Last Edited: 2009-11-04 22:30:22
November 04 2009 22:30 GMT
#20
On November 05 2009 05:54 iSiN wrote:
you program with C# peter...this makes me sad

Programming in C# is part of my job. What's wrong with that?
iSiN
Profile Blog Joined March 2009
United States1075 Posts
November 04 2009 23:47 GMT
#21
On November 05 2009 07:30 HnR)Insane wrote:
Show nested quote +
On November 05 2009 05:54 iSiN wrote:
you program with C# peter...this makes me sad

Programming in C# is part of my job. What's wrong with that?

I'm so sorry.
(I hate C# so much but then again I hate java and I'm pretty sure I'll be programming in java when I get in the field)
Grouty @HoN/PCKJ <--<333 || Jaedong Fan Cafe GFX
Artosis *
Profile Blog Joined June 2004
United States2140 Posts
November 05 2009 01:02 GMT
#22
eulerarchive.org
Commentatorhttp://twitter.com/Artosis
Normal
Please log in or register to reply.
Live Events Refresh
Next event in 4h 10m
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
WinterStarcraft629
Nina 175
NeuroSwarm 121
ProTech74
StarCraft: Brood War
sSak 222
Bale 64
Movie 13
Shine 12
Icarus 10
yabsab 9
Dota 2
LuMiX1
League of Legends
JimRising 723
Counter-Strike
Stewie2K888
semphis_49
Super Smash Bros
Mew2King82
Other Games
summit1g7661
shahzam786
C9.Mang0342
Maynarde130
ViBE2
Organizations
Other Games
gamesdonequick1175
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 12 non-featured ]
StarCraft 2
• practicex 24
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
League of Legends
• Rush1929
Upcoming Events
Sparkling Tuna Cup
4h 10m
Afreeca Starleague
4h 10m
Soulkey vs Barracks
EffOrt vs Rush
Monday Night Weeklies
10h 10m
Afreeca Starleague
1d 4h
BeSt vs Alone
Queen vs Bisu
The PondCast
3 days
RSL Revival
3 days
Cure vs SHIN
Reynor vs Zoun
RSL Revival
4 days
Classic vs TriGGeR
ByuN vs Maru
Online Event
4 days
BSL Team Wars
4 days
Team Bonyth vs Team Dewalt
BSL Team Wars
4 days
[ Show More ]
RSL Revival
5 days
Maestros of the Game
5 days
Cosmonarchy
5 days
Bonyth vs Dewalt
[BSL 2025] Weekly
5 days
RSL Revival
6 days
Maestros of the Game
6 days
BSL Team Wars
6 days
Liquipedia Results

Completed

Copa Latinoamericana 4
SEL Season 2 Championship
HCC Europe

Ongoing

BSL 20 Team Wars
KCM Race Survival 2025 Season 3
BSL 21: BSL Points
ASL Season 20
CSL 2025 AUTUMN (S18)
LASL Season 20
RSL Revival: Season 2
Maestros of the Game
Chzzk MurlocKing SC1 vs SC2 Cup #2
BLAST Open Fall 2025
BLAST Open Fall Qual
Esports World Cup 2025
BLAST Bounty Fall 2025
BLAST Bounty Fall Qual
IEM Cologne 2025
FISSURE Playground #1

Upcoming

2025 Chongqing Offline CUP
BSL Polish World Championship 2025
BSL Season 21
BSL 21 Team A
EC S1
BLAST Rivals Fall 2025
IEM Chengdu 2025
PGL Masters Bucharest 2025
Thunderpick World Champ.
MESA Nomadic Masters Fall
CS Asia Championships 2025
ESL Pro League S22
StarSeries Fall 2025
FISSURE Playground #2
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2025 TLnet. All Rights Reserved.