Challenge: Largest Reciprocal Cycle

Posted on: June 9, 2017 2:05:16 AM
This is another project euler challenge that states:

A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:

 1/2 = 0.5 1/3 = 0.(3) 1/4 = 0.25 1/5 = 0.2 1/6 = 0.1(6) 1/7 = 0.(142857) 1/8 = 0.125 1/9 = 0.(1) 1/10 = 0.1

Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.

Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.

This problem required me to do quite a bit of research on decimals with recurring cycles. I came across a wikipedia article that led me to Fermat's Little Theorem to get the number of digits in the cycle, aka, the period. From there, the problem was easy to solve.
Program.cs
```using Common.Math;
using System;

namespace ProjectEuler_26
{
internal class Program
{
public static void Main(string[] args)
{
Tuple result = new Tuple(0, 0);

// start by getting primes up to 1000
var primes = Eratosthenes.GetPrimes(1000);

// loop backwards
for (int i = primes.Length - 1; i >= 0; i--)
{
int count;

// we know that the most a cyclical decimal will repeat is d-1
if ((count = GetCyclicalCount(primes[i])) == primes[i] - 1)
{
result = new Tuple(count, primes[i]);
break;
}
}

Console.WriteLine(\$"The value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part is {result.Item2} with {result.Item1} numbers in the cycle.");
}

private static int GetCyclicalCount(int prime)
{
int period = 1;

// using Fermat's Little Theorim you can get the count of numbers in the cycle referred to as a period
// Fermat's Little Theorim is defined as a^p=a%p
// where a is the number base and p is a prime of that number base
// this means that the count of cyclical numbers is the first modular power where the period test is not 1

while (ModularPow(10, period, prime) != 1)
{
period++;
}

return period;
}

private static int ModularPow(int @base, int exponent, int modulus)
{
if (modulus == 1) return 0;

int result = 1;
for (int i = 1; i <= exponent; i++)
{
result = (result * @base) % modulus;
}

return result;
}
}
}
```
The code is pretty well documented and explains what it's doing at just about every step. Enjoy!

A lot of useful information as always, thank you and best regards!

GilbertsAx September 16, 2021 6:34:48 AM

It is very good that you can find more and more information on this topic on the Internet.

Andrewjes September 16, 2021 9:53:02 AM

It is worth ensuring that such websites have more and more content. Keep it up!

ReubenGrina September 25, 2021 1:31:44 AM

I go to see daily some websites and sites to read articles, but this weblog provides feature based posts. situs agen slot

Cole February 24, 2022 3:22:10 PM

single gay men chat line highpoint nc [url="https://chatcongays.com"]choose a gay video chat free[/url] gay phone chat manhole

GenniesrPa September 16, 2022 12:10:46 AM

gay furry chat [url="https://chatcongays.com"]gay black man chat[/url] hairy gay men chat free

GenniesrPa September 16, 2022 2:32:26 AM

serial

Coral September 19, 2022 10:52:00 AM

buy an essay online [url="https://au-bestessays.org"]english essay helper[/url] customized essay writing

MarrissrPa September 20, 2022 12:51:09 AM

custom essay cheap [url="https://au-bestessays.org"]i need help writing my essay[/url] essay help chat room

MarrissrPa September 20, 2022 1:09:29 AM

write my essay service [url="https://bestcampusessays.com"]reliable essay writing service[/url] best custom essay

DorolisasrPa September 20, 2022 8:03:21 PM

essay writers toronto [url="https://bestcampusessays.com"]personal statement essay help[/url] buy college essays online

DorolisasrPa September 20, 2022 8:22:03 PM

A lot of thanks for all your hard work on this blog and alo try to [url=https://www.kizi10.org] play kizi10 games [/url]. Ellie takes pleasure in setting aside time for investigations and it’s really simple to grasp why. My spouse and i hear all concerning the compelling method you deliver powerful items on this website and as well strongly encourage participation from website visitors on the area plus my princess is undoubtedly being taught so much.

KizdiZ September 21, 2022 12:44:13 PM

college entrance essay writing service [url="https://besteasyessays.org"]help with writing essay[/url] essay editing service online

MartysrPa September 21, 2022 6:24:45 PM

essay writing websites [url="https://besteasyessays.org"]help me write a essay[/url] english essay writing service

MartysrPa September 21, 2022 6:42:12 PM

essay writers wanted [url="https://bestessayreviews.net"]custom college essay writing service[/url] how to write my essay

MerolasrPa September 22, 2022 2:23:31 PM

essay title help [url="https://bestessayreviews.net"]good essay writing service[/url] help writing essays

MerolasrPa September 22, 2022 2:43:01 PM

custom essay paper [url="https://bestessaysden.com"]custom essays for sale[/url] helping others essays

AshlensrPa September 23, 2022 10:27:27 AM

essay writer funny [url="https://bestsessays.org"]essay writer website[/url] KeyWord

CharitasrPa September 24, 2022 11:45:15 PM

essay help chat [url="https://bestsessays.org"]essay write service[/url] college essay help online

CharitasrPa September 25, 2022 12:02:26 AM

scholarship essay writing help [url="https://buyacademicessay.com"]cheap essays for sale[/url] best essay writing company

NanicesrPa September 25, 2022 6:43:07 PM

best custom essay service [url="https://buyacademicessay.com"]best online essay writer[/url] write my essay generator

NanicesrPa September 25, 2022 7:00:20 PM

best essay cheap [url="https://buy-eessay-online.com"]personal essay writing service[/url] essay help chat

ChelsaesrPa September 26, 2022 2:23:29 PM

which essay writing service is the best [url="https://buy-eessay-online.com"]help on essays[/url] i need help writing an essay

ChelsaesrPa September 26, 2022 2:41:08 PM

online essay editing service [url="https://buytopessays.com"]homework essay help[/url] essay writing assignment help

PennysrPa September 27, 2022 9:33:06 AM

essay help pros [url="https://buytopessays.com"]where can i buy an essay[/url] Who wants to write my essay

PennysrPa September 27, 2022 9:52:14 AM

buy essay cheap [url="https://cheapessaywritingservice1.com"]write my essay for money[/url] essay help chat

TammiesrPa September 28, 2022 5:21:13 AM

fast essay writing service [url="https://customcollegeessays.net"]custom essay writing reviews[/url] college admission essay service

AntoniesrPa September 29, 2022 1:19:09 AM

personal statement essay help [url="https://customcollegeessays.net"]academic essay writing service[/url] buy an essay online

AntoniesrPa September 29, 2022 1:35:03 AM

buy an essay online cheap [url="https://customessays-writing.org"]top ten essay writing services[/url] best essay website

RhiamonsrPa September 29, 2022 8:56:54 PM

help to write an essay [url="https://customessays-writing.org"]essays on the help[/url] i cant write my essay

RhiamonsrPa September 29, 2022 9:12:41 PM

essay help 123 [url="https://customessaywwriting.com"]help essays[/url] automatic essay writer

CharosrPa September 30, 2022 4:03:41 PM

best college essay help [url="https://customs-essays-writing.org"]help writing essays for college[/url] automatic essay writer

DronasrPa October 1, 2022 10:26:45 AM

admission essay services [url="https://firstessayservice.net"]academic essay writer[/url] looking for someone to write my essay

TwylasrPa October 2, 2022 5:56:02 AM

academic essay writing help [url="https://firstessayservice.net"]custom writing essay service[/url] essay writing services toronto

TwylasrPa October 2, 2022 6:13:07 AM

help writing scholarship essays [url="https://geniusessaywriters.net"]essays help[/url] act essay help

LeilahsrPa October 3, 2022 2:41:47 AM

best online essay writing service [url="https://howtobuyanessay.com"]service to others essay[/url] custom my essay

CthrinesrPa October 4, 2022 12:51:55 AM

essay writers canada [url="https://lawessayhelpinlondon.com"]service essay writing[/url] online essay writing service review

GinniesrPa October 9, 2022 12:28:47 PM

cheap essay writing service online [url="https://lawessayhelpinlondon.com"]cheap custom essay writing services[/url] persuasive essay helper

GinniesrPa October 9, 2022 12:47:19 PM

the help essay questions [url="https://ukessayservice.net"]top essay writing services[/url] best college essay editing service

VivienesrPa October 11, 2022 6:48:29 PM

cheap custom essays [url="https://writemyessaycheap24h.com"]top rated essay writing websites[/url] scholarship essay help

EastersrPa October 13, 2022 9:50:17 AM

write my admissions essay [url="https://writemyessaycheap24h.com"]professional essay writers[/url] best custom essay website

EastersrPa October 13, 2022 10:08:35 AM

https://prednisoneall.top/

HpfGPDP October 30, 2022 11:54:35 AM

Our website [url=https://www.bestcrazygames.com]play best crazy games[/url] has begun to discharge stylish games and driving games, and reborn opportunities to from them here are added. We come quotidian driving games nearby trucks, bikes, racing, cars, and other channel types. Another recommended class is games seeking girls with fashion dress-up and make-up. If you be sure what is playing these days is the most qualified predominant .io games, numerous developers released chic io games on the browser in pattern years, such as hole.io, venge.io, voxiom.io, and much more .io super games. Also, we are striving to count up some uncordial new kid erudition games to amend the leader and reflective abilities. Also, some other types of car games online inclination improve your reflex and timing abilities.

Baorier November 5, 2022 10:44:06 AM

Our website [url=https://www.crazygamesonline.com/]crazy games online[/url] and we classify our multiplayer games free online into the 11 most preferred classifications: driving, capturing, clicker, and.io. We started as a driving game internet site and have collected around 1000 of the best driving games. These multiplayer games best include car games, bike games, monster trucks games, and any other two-player games you can consider. Later our shooting games have taken off.

Caorier November 5, 2022 3:52:29 PM

A lot of thanks for all your hard work on this blog and alo try to [url=https://www.kizi10.org] play kizi10 games [/url]. Ellie takes pleasure in setting aside time for investigations and it’s really simple to grasp why. My spouse and i hear all concerning the compelling method you deliver powerful items on this website and as well strongly encourage participation from website visitors on the area plus my princess is undoubtedly being taught so much.

KizdiZ November 9, 2022 1:44:46 PM

english essay helper [url="https://bestcampusessays.com"]write my essay paper[/url] buy essay paper

DorolisasrPa November 19, 2022 7:16:50 AM

help with essay papers [url="https://besteasyessays.org"]help with argumentative essay[/url] i need help with writing an essay

MartysrPa November 20, 2022 1:42:02 PM

online essay writing services [url="https://besteasyessays.org"]help writing college application essay[/url] history essay writing service

MartysrPa November 20, 2022 2:07:25 PM

top rated essay writing services [url="https://bestessayreviews.net"]write my essay for cheap[/url] cheap essays writing service

MerolasrPa November 21, 2022 9:30:13 PM

best essays writing service [url="https://bestessaysden.com"]college admission essay help[/url] essays writing services

AshlensrPa November 23, 2022 6:49:48 AM

buy college essays online [url="https://bestsessays.org"]custom essay[/url] reviews for essay writing services

CharitasrPa November 24, 2022 2:05:56 PM

NanicesrPa November 25, 2022 11:27:40 PM

NanicesrPa November 25, 2022 11:51:29 PM

casino jeux de machines a sous gratuites le meilleur casino du monde jeux casino en ligne legal jeu de casino gratuit a telecharger code bonus casino en ligne jouer au blackjack au casino jeu casino francais gratuit avec bonus secret roulette casino casino comment gagner au machine a sous astuce pour gagner au machine a sous casino technique gagnante roulette regle a roulette comment jouer machine a sous casino jeux casino gratuit 3 rouleaux gagner a la roulette a coup sur blackjack sans argent martingale roulette casino en ligne casino argent reel bonus sans depot jeux de roulette gratuit sans inscription regle poker 5 carte en main methode roulette casino carte poker texas jeux de casino gratis casino en ligne video poker jeux de casino en ligne autorise en france casino france en ligne jeu de roulette au casino casino roulette en ligne live black jack casino regle code bonus casino en ligne jeu gratuits casino jeux de casino gratuit avec bonus casino belge gratuit casino en ligne en france legal casino machine a sous gratui blackjack gratuit en ligne multijoueur comment arreter de jouer au casino en ligne casino jeux virtuelle machine a sous dragonara casino live roulette jeux casino gratuit buffalo casino gratuit solitaire machine a sous sans telechargement regle a roulette casino gratuit machines a sous sans inscription strategie de base blackjack france jeux casino poker gratuit jouer a la roulette casino payant en ligne casino en ligne avec paysafecard mobile jeux de casino bonus casino belgique technique roulette casino douzaine machine a sous gratuites casino https://www.gaamble.net/jeux-casino-poker/ astuce roulette https://www.gaamble.net/jeux-gratuit-de-casino/ technique gagnante roulette https://www.gaamble.net/casino-machine-a-sous-en-lignepayant/ nouveau bonus sans depot casino https://www.gaamble.net/casino-machine-a-sous-gratuites-sans-telechargement/ puissance carte poker https://www.gaamble.net/blackjack-gratuit-en-ligne-multijoueur/ casino avec depot paypal https://www.gaamble.net/casino-en-ligne-meilleur/ astuce jeu mines casino https://www.gaamble.net/casino-roulette-en-ligne-live/ jeux gratuit du casino https://www.gaamble.net/live-casino-en-ligne/ casino en ligne francais avec bonus de bienvenue sans depot https://www.gaamble.net/jeu-de-la-roulette-regle/ jeux casino liste https://www.gaamble.net/carte-de-france-des-casinos-machine-a-sous/ casinos en ligne bonus sans depot https://www.gaamble.net/jeux-casino-tour-gratuit/ casino gratuit en ligne roulette https://www.gaamble.net/bonus-de-bienvenue-casino-sans-depot/ casino fr jeu https://www.gaamble.net/jeux-de-roulette-gratuit/ jeux poker 5 cartes gratuit https://www.gaamble.net/astuce-casino-en-ligne/ casino en ligne gratuit a telecharger https://www.gaamble.net/meilleur-casino-live/ comment bien jouer au blackjack au casino https://www.gaamble.net/logiciel-blackjack-gratuit/ aviator jeux casino avis https://www.gaamble.net/jeu-gratuits-casino/ poker avec 4 cartes en main https://www.gaamble.net/jeu-du-poulet-casino/ poker solitaire mobile 5 cartes https://www.gaamble.net/application-jeu-de-roulette-gratuit/ roulette tips casino https://www.gaamble.net/casino-et-paypal/ casino jeu gratuit en ligne https://www.gaamble.net/jeu-qui-rapporte-le-plus-au-casino/ regle du blackjack carte https://www.gaamble.net/jeux-de-la-roulette-casino-gratuit/ roulette astuce https://www.gaamble.net/jouer-casino-gratuit/ casino zurich en ligne https://www.gaamble.net/casino-en-ligne-roulette-en-direct/ comment gagner au casino roulette https://www.gaamble.net/casino-en-ligne-gratuit-avec-bonus-sans-depot/ astuce casino roulette electronique

Eddie December 9, 2022 2:34:00 PM

Правильно написать новость – настоящее искусство. Но научиться этому не сложно. Прежде чем начнём раскрывать алгоритм написания, вспомним, что такое новость. Предлагаем познакомиться с примером как правильно писать новость на примере про новости Кыргызстана . Детальнее на нашем сайте - https://rabbitroom.com/members/edsas19572/profile/ . Новость – актуальная, свежая информация, полученная из Ваших собственных источников. При написании новости Вы должны держать в голове следующие вопросы: Кто? Что? Когда? Где? Почему? Как? Такой способ поможет Вам не забыть некоторые аспекты, которые нужно обязательно упомянуть в своей статье. Новостная заметка — самый важный жанр, основа всей журналистики новостная заметка, или говорят «информационная заметка». Как мы уже писали в первом уроке, в заметке вы кратко рассказываете о каком-то произошедшем событии. бъем новостной заметки небольшой меньше одной страницы печатного текста. Написать информационную заметку не сложно. Не забывайте, в журналистском материале должен быть информационный повод (это событие, что-то что произошло например, открылся детский сад, закрылся завод или в ваш город приехал известный человек). В новостной заметке должен быть заголовок, лид, подробности и бэкграунд. Каждому из этих компонентов заметки будет посвящен отдельный урок. Пока что запомним: Заголовок это название материала, он привлекает внимание читателя, даёт первичную информацию. Заголовок новостной заметки это как вывеска у магазина. Это анонс материала. В лиде мы кратко сообщаем о произошедшем событии и упоминаем о чем пойдет речь далее. Два-три предложения для лида вполне достаточно. Никаких лишних подробностей в нём не должно быть. Бэкграунд это заключительная часть новостной заметки, в которой мы можем рассказать о предыстории этого события или дать справочную информацию по рассматриваемой теме. Уместите бэкграунд в небольшой абзац. Чтобы научиться хорошо писать, делать качественные журналистские материалы, нужно читать прессу. Сейчас многие издания имеют свои сайты и при наличии интернета вы можете в любое время ознакомиться с последними новостями. Я рекомендую вам читать каждый день газетные статьи и новости информационных агентств. Выбирайте ту информацию, которую вам интересно читать, которая будет вам полезна. Отмечайте, запоминайте удачные заголовки, правила оформления цитат и другие детали. Мы не будем рекомендовать конкретные издания, поскольку вы живете и работаете в другом городе или даже в другой стране. Вам проще определиться с выбором СМИ.

Gloria February 4, 2023 4:16:16 AM

Производитель спецодежды в Москве защита сварщика (http://specodegdaoptom.ru/) - купить оптом спецодежду.

Lukas June 17, 2023 11:39:02 AM

Hi there everyone, it's my first pay a visit at this web site, and article is really fruitful in favor of me, keep up posting these types of articles or reviews. http://noriapp.co.kr/bbs/board.php?bo_table=1_bg_slider03&wr_id=580419

tanie pozycjonowanie stron www October 4, 2023 4:49:05 PM

Производитель спецодежды в Москве магазин спецодежды в москве - купить оптом спецодежду.

Lucinda November 10, 2023 2:54:07 PM

Производитель спецодежды в Москве магазин спецодежды в москве - купить оптом спецодежду.

Lewis November 12, 2023 1:55:55 AM

Order accutane uk — american express online

Shannon November 13, 2023 9:54:35 AM

https://www.vidozahost.com/

AdolfoReomo December 7, 2023 3:16:59 PM

EllisDob December 8, 2023 8:48:18 AM

Contact Me
Recent Blog Activity
Blog Archive