text:
Implement this key cipher
Implement this key cipher
Goal
Use the algorithm (explained in the Algorithm section) to implement a certain cipher.
The program must read input from STDIN or the closest available equivalent, use the algorithm to generate the ciphertext and a key.
The ciphertext and the key will be written to STDOUT or the closest available equivalent. Any format is allowed, as long as it outputs the ciphertext and the key.
Algorithm
Convert the characters in the string into the respective ASCII values. For example:
Hello -> 72 101 108 108 111
Next, you will need to generate a key as long as the string with random numbers in the range of 0-9.
Hello -> 62841
Add the integers in the random number sequence to the ASCII values of the string. In the above examples, 72 would become 78, and 101 would become 104.
72 + 6 = 78, 101 + 2 = 103, 108 + 8 = 116, etc
Next, convert the new values back to characters. In the above examples, the text Hello has become Ngtpp.
Examples
(These are simply examples of what the output might look like. The output can and will vary.)
Hello World

Lfrlu)_supg
41606984343

This will be encoded

Zhjs$~koo gj$iuhofgj
60104723305544750226

Rules

You can assume that the input will only contain characters in the range a-z, A-Z, and spaces.
Submissions must be full programs or functions.
Submissions will be scored in bytes.
Standard loopholes are forbidden.
This is code-golf, so the shortest code wins.

(This is one of my first challenges, if there's something wrong with it, feel free to tell me how I could improve it.)

This challenge looks good to me, except for a couple of thoughts. 1. Is a function allowed instead of a full program? A related question is could the values be returned instead of printed? 2. You said preferably with the format (ciphertext)\n(key). "preferred features" and code golf don't mix very well. Your should make that mandatory or allow other output formats. 3. Does the key have to be printed without spaces? What about printing it in list format, e.g. [0, 5, 2, ...]?

Can the key have leading zeroes?

Can I print the key first and then the cipher text?

@DJMcMayhem I updated the challenge.

@TheBikingViking Updated.

@Maltysen Yes, you can. They have to be separated with a newline though.

@TimmyD Yep, it was a typo. I'll update it

@DJMcMayhem Well, I changed the rules a little, you can post it now.

@m654 Thanks! Generally it's best to go with a very permissive IO format. I've actually already posted it, but I'll edit it to be shorter now.

Nice first challenge but I'm not so sure on the strict IO formats. Usually functions are allowed and usually answers can read from one of the accepted IO methods. This includes outputting an array with the items

Do the digits of the key have to be generated with an uniform distribution?

I made the format more permissive. @Dennis, no, it doesn't have to. Pseudorandom numbers are alright.

Pseudo-random is not the same as not uniform. A non-uniform distribution could generate 0 with probability 1/2, 1 with probability 1/3, etc.

Oh, by the way, convert the new ASCII values back to characters isn't entirely correct. If you add 9 to an ASCII code point, the result could be an integer larger than 127, so it would fall outside the ASCII range. Also, you say the input will only contain characters in the range a-z and A-Z, but your examples have spaces.

@Dennis ._. Fixed.

Uh ... 101 + 2 is 103, not 104. :-)

@YetiCGN Haha, sorry. It was a typo.

I though as much. ;-) You still have 104 in the text, in the line above it.

Jelly, 12 9 bytes
⁵ṁX€’Ṅ+OỌ

Try it online!
How it works
⁵ṁX€’Ṅ+OỌ  Main link. Argument: s (string)

⁵             Set the return value to 10.
 ṁ            Mold; create an array of 10's with the length of s.
  X€          Pseudo-randomly pick a integer between 1 and 10, for each 10.
    ’         Decrement, so the integers fall in the range [0, ..., 9].
     Ṅ        Print the key, as an array, followed by a linefeed.
      +O      Add the integers to the ordinals (code points) of s.
        Ọ     Unordinal; convert back to characters.

Python 3, 130 bytes
Thanks to @Rod for pointing out a bug
from random import*
def f(x):l=10**len(x);k=str(randint(0,l-1)+l)[1:];print(''.join(chr(ord(i)+int(j))for i,j in zip(x,k))+'\n'+k)

A function that takes input via argument as a string and prints to STDOUT.
How it works
from random import*  Import everything from the random module
def f(x):            Function with input string x
l=10**len(x)         Define l for later use as 10^length(x)
randint(0,l-1)+l     Generate a random integer in the range [0, l-1] and add l, giving a
                     number with l+1 digits...
k=str(...)[1:]       ...convert to a string and remove the first character, giving a key of
                     length l that can include leading zeroes, and store in k
for i,j in zip(x,k)  For each character pair i,j in x and k:
chr(ord(i)+int(j))    Find the UTF-8 code-point (same as ASCII for the ASCII characters),
                      add the relevant key digit and convert back to character
''.join(...)         Concatenate the characters of the ciphertext
print(...+'\n'+k)    Add newline and key, then print to STDOUT

Try it on Ideone

your key generator do not generates keys starting with 0. increasing the boundaries by a factor of 10 and removing the 1st digit should fix:
m=10**len(x);k=str(randint(m,m*10))[1:]; and you even save a byte in the process c:

@Rod Thanks for pointing out the bug. That won't save any bytes, however, since randint is inclusive, meaning that you would need to do m*10-1. I've just thought of a way to fix it for the same byte count.

Pyth - 16 bytes
Waiting for decision by OP on the output formats.
sCM+VCMQKmOTQjkK

Test Suite.

I decided on the format.

Actually, 17 bytes
;`X9J`M;(O¥♂cΣ@εj

Try it online!
Explanation:
;`X9J`M;(O¥♂cΣ@εj
;                  dupe input
 `X9J`M            for each character in input copy:
  X9J                discard the character, push a random integer in [0, 9]
       ;           duplicate the offset array
        (O         bring input to top of stack, ordinal array
          ¥♂c      pairwise addition with offset array, turn each ordinal into a character
             Σ     concatenate
              @εj  concatenate the copy of the offset array

PowerShell v2+, 79 77 bytes
param($n)-join(($x=[char[]]$n|%{0..9|Random})|%{[char]($_+$n[$i++])});-join$x

Takes input $n, loops over every character and gets a Random element from 0..9 each iteration. Stores those numbers (as an array) into $x. Pipes that array into another loop. Each iteration, takes the current element $_, adds it to the positional char sliced out of $n (implicit char-to-int cast), then re-casts as [char]. Leaves that on the pipeline. That's encapsulated in parens and -joined together to form the word. That's left on the pipeline. Additionally, the number $x is also -joined together and left on the pipeline. Those are implicitly printed with a Write-Output at the end of execution, which results in them being printed with a newline by default.
Example
PS C:\Tools\Scripts\golfing> .\implement-this-key-cipher.ps1 'Hello World!'
Lhoot(Yt{mf"
433358259121

CJam - 14 bytes
When I saw the ascii code math, I knew I had to write a CJam answer.
q_{;Amr}%_@.+p

Try it online here.

MATL, 13 bytes
"10r*]v!kGy+c

The output looks like this:
9 5 8 2 1
Qjtnp

Try it online!
Explanation:
"    ]          % For each character:
 10             % Push a 10 onto the stack
   r            % Push a random float in [O, 1)
    *           % Multiply. This essentially the same thing as pushing a number in [0, 10)
      v!k       % Join all of these together, and take the floor
         G      % Push the input again
          y     % Duplicate the array of random numbers
           +    % And add these together. Since MATL treats strings as an array of chars, we don't need to explicitly convert types
            c   % Display as string

I'm not sure if that's the right format...

@Leaky Nun I changed the rules a little.

@m654 Where did you say there can be spaces between the values?

@LeakyNun Originally there was a rule against them but I removed it.

@m654 You haven't allowed it either.

Good idea to use the loop. It's actually shorter than the multiple-input version of r or Yr

@LuisMendo I've never grokked multiple input versions well. How exactly do you call that? I tried tn&r but that doesn't seem to work right. Same thing with $r and #r

Also, isn't there a shortcut for 10?

I haven't defined & for r yet. So to generate the 1x10 random array without loop you'd need somethinkg like n1H$r!. This is: push input length (n), push 1, next function will take two input arguments (H$), call r with arguments "length" and "1" to produce the random array, transpose (!). There is no shortcut for 10. 2# would specify two outputs for the next function (but r doesn't have a two-output version). These are the possible signagtures of r

05AB1E, 18 17 bytes
vžh.RDyÇ+ç`?}J¶?,

Explanation
v           }      # for each char in input
 žh.RD             # push 2 copies of a random number in [0..9]
      yÇ+          # add 1 copy to the current chars ascii value
         ç`?       # convert to char, flatten and print
             J     # join stack (which contain the digits of the key)
              ¶?,  # print a newline followed by the key

Try it online

C#, 252 247 245 232 216 Bytes
The size is pretty bad compared to the other solutions but nevertheless...
using System;using System.Linq;class p{static void Main(){var c="";var i=Console.ReadLine();var r=new Random();for(int b=0;b++<i.Count();){int d=r.Next(10);Console.Write((char)(i[b]+d));c+=d;}Console.Write("\n"+c);}}

This is my second ever answer to a codegolf and I'm quite a beginner considering C# so I'd appreciate to hear how to get it shorter :)
Ungolfed:
using System;
using System.Linq;

class p
{
    static void Main()
    {
        var c = "";
        var i = Console.ReadLine();
        var r = new Random();
        for (int b = 0; b++ < i.Count();)
        {
            int d = r.Next(10);
            Console.Write((char)(i[b] + d));
            c += d;
        }
        Console.Write("\n" + c);
    }
}

Saved 5 Bytes thanks to @FryAmTheEggman
Saved 2 Bytes thanks to @theLambGoat
Saved 7 Bytes by removing static from class p
Saved 24 Bytes thanks to @milk

The trick is not to compare with other languages ;) I'm not particularly well versed in C# golf, but can you do b++<i.Count() and leave the third clause empty? Also, I don't think you need a trailing newline, so the last call to WriteLine could be Write instead.

I'm also not well versed in C# but I think you can move the =r.Next(10) up to the declaration of d and save on a set of parenthesis in the write. Or does the random not return an int so you can't do that?

I think I can do that, let me check

You can replace types with var. ie- var c= instead of string c= to shave a few bytes.

Why not leave the result of Console.ReadLine() as string? i.Length is shorter than i.Count(), you won't need System.Linq. string has a char indexer. Also creating new Random objects in the loop is less bytes: new Random().Next(10).

Creating new Randoms for every random number does always give me the same number for each iteration then, which is certainly not what OP wants, but thanks anyway :)

CJam, 11 bytes
Nq{Amr_o+}/

Try it online!
How it works
N            Push a linefeed on the stack.
 q           Read all input from STDIN and push it on the stack.
  {      }/  For each character in the input:
   Amr       Pseudo-randomly pick an integer in [0 ... 9].
      _o     Print a copy.
        +    Add the integer to the character.
             (implicit) Print the linefeed, followed by the modified characters.

Python 3, 112 bytes
c is a function that returns the encrypted text and the key
from random import*
c=lambda t:map(''.join,zip(*[(chr(a+b),str(b))for a,b in((ord(i),randint(0,9))for i in t)]))

Here is a code that does the same thing and is a bit more readable
def encrypt(text):
    # keep the codes of the letters in the input and a random key
    # that will be used later to encrypt this letter
    letter_and_key = ((ord(letter),randint(0,9)) for letter in text)

    # encrypt the letter and keep the key used as a string
    output_and_key = [(chr(letter_code+key), str(key))
                      for letter_code, key in letter_and_key]

    # At this point the values are kept in the format:
    # [(firstletter, firstkey), (secondletter, secondkey), ...]

    # to reorder the list to be able to output in the format "text key"
    text, key = map(''.join, zip(*output_and_key))

    # same as print(*output_and_key)
    return text, key

Output:
>>> text, key = c('Hello World')
>>> print(text, key, sep='\n')
Liuot#`oylk
44935390707

Welcome to this site!

PHP, 63 86 82 bytes
Edit: forgot to print the key...
Thanks to Alex Howansky for saving me 4 bytes.
for(;$i<strlen($a=$argv[1]);$s.=$r)echo chr(ord($a[$i++])+$r=rand(0,9));echo"
$s";

Input is given through a command line argument. Takes each character in the string and adds a random int from 0-9 to its ASCII code, then converts the code back to ASCII. Every random number is appended to $s, which is printed at the end.

You need to print the key as well.

You can put the $s.=$r after the 2nd semi in the for loop, saving a byte because you can dump its trailing semi. Then your loop will only be one statement so you can cut out the wrapping braces, saving 2 more bytes. Then at the end, you can put the $s inside the quoted string saving the . operator for one more byte. :)

@AlexHowansky: That's very true. Thanks

J, 32 bytes
<@:e,:~[:<[:u:3&u:+e=.[:?[:$&10#

python equivalent:
from random import randint
def encrypt(message):
    rand_list = list(map(lambda x: randint(0, 9), range(len(message))))
    return (''.join(list(map(lambda x,y: chr(x+y), rand_list, map(ord, message)))), rand_list)

Perl, 34 bytes
Includes +1 for -p
#!/usr/bin/perl -p
s%.%$\.=$==rand 10;chr$=+ord$&%eg

Perl, 65 bytes
for(split'',$ARGV[0]){$;.=$a=int rand 9;$b.=chr$a+ord}say"$b\n$;"

Took me awhile to figure out how to get the input without a new line at the end. Takes it as a command line arg

Your solution has some problems. Input is not read form STDIN, $; does not start empty so it prints the old content and the rand can never generate 9. They are easy to fix and using STDIN will make your code shorter :-)

@TonHospel Usually input requirements are loose and args are acceptable over STDIN and while taking input from STDIN is shorter, having to remove the newline from it makes it longer. And while rand does generate numbers < 9, Perl's int method rounds rather than floors so anything >=8.5 should end up as 9

Input requirements usually are loose, but here it wasn't. Getting non newline from STDIN is easy: <>=~/./g. And no, int in perl truncates towards 0, it doesn't round. perl -wle 'print int 8.6' outputs 8

Python 2, 84 99 bytes
def f(x):y=`id(x)**len(x)`[1:len(x)+1];return''.join(map(chr,[ord(a)+int(b)for a,b in zip(x,y)])),y

Uses the id() value of the string to generate random numbers.
Try it

You have to output the key as well as the ciphertext.

@TheBikingViking don't know how I missed that. Thanks--fixed

I think that this also has the same problem as an earlier version of my Python answer; it never produces keys with leading zeroes.

@TheBikingViking Fixed again

change map(chr,[ord(a)+int(b)for a,b in zip(x,y)]) to map(lambda x,y:chr(ord(x)+int(y)),x,y)? that should save something

Senva, 74 bytes
Here is the shortest program I've made :
2'(`>0.>{@}0'{v}2-2'0,{@}1'{v}0'{+}{'}9%+{^}{1-}1'"{+}{~}>$10.~0'2+"0,-:>$

A little explanation ? (Note: BM means Back-Memory) :
// === Input and informations storing ===

2'  // Go to the 3rd cell (the two first will be used to store informations)
(   // Ask the user for a string (it will be stored as a suite of ASCII codes)
`   // Go the end of the string
>   // Make a new cell
0.  // Put a 0 to mark the end of the string
>   // Make a new cell, here will be stored the first random number
{@} // Store its adress in BM
0'  // Go to the 1st cell
{v} // Paste the adress, now the 1st cell contains the adress of the first random number
2-  // Subtract 2 because the string starts at adress 2 (the 3rd cell)
2'  // Go to the 3rd cell (where the string begins)

// === String encryption and displaying ===

0,  // While the current cell doesn't contain 0 (while we didn't reach the string's end)
  {@}  // Store the character's adress into the memory
  1'   // Go to the 2nd cell
  {v}  // Paste the value, now the 1st cell contains the adress of the current char
  0'   // Go to the 1st cell
  {+}  // Add the adress of the first random number to the current char adress
  {'}  // Go to this adrses
  9%+  // A random number between 0 and 10
  {^}  // Store this number in BM
  {1-} // Decrease BM (random number between 0 and 9)
  1'   // Go to the 1st cell
  "    // Go to the adress pointed by the cell (the adress of the current char)
  {+}  // Add it to the random number value
  {~}  // Display it as an ASCII character
  >    // Go to the next cell (the next character)
$   // End of the loop
10. // Set the new line's ASCII code into the current cell (which is now useless, so it can be overwritten)
~   // Display the new line
0'  // Go to the first cell
2+  // Add 2 to the adress, because we are not in the string loop : we cancel the 2 substraction
"   // Go to the pointed adress (the first random number's one)

// === Display the random numbers ===

0,  // While we didn't reach the end of the random numbers suite
    // That was why I stored numbers between 1 and 10, the first equal to 0 will be the end of the suite
  - // Decrease it (number between 0 and 9)
  : // Display the current random number as an integer
  > // Go to the next cell (the next number)
$ // End of the loop

That appears bigger now, true :p ? Maybe it's possible to optimize this code, but for the moment that's the shortest I've found.

C#, 174 bytes
using static System.Console;class b{static void Main(){var c=new System.Random();var d="\n";foreach(var e in ReadLine()){var f=c.Next(10);Write((char)(e+f));d+=f;}Write(d);}}

Ungolfed:
using static System.Console;

class b
{
    static void Main()
    {
        var c = new System.Random();
        var d = "\n";

        foreach (var e in ReadLine())
        {
            var f = c.Next(10);
            Write((char)(e + f));
            d += f;
        }

        Write(d);
    }
}

Pretty straightforward, really.

Perl 6: 55 or 70 bytes
As an anonymous function that takes a string parameter, and returns a list of two strings (54 characters, 55 bytes):
{my @n=^9 .roll(.ords);(.ords Z+@n)».chr.join,@n.join}

As a program that reads from STDIN and writes to STDOUT (69 characters, 70 bytes):
my @a=get.ords;my @n=^9 .roll(@a);say (@a Z+@n)».chr.join;say @n.join


text:
Smallest positive number whose y-th power is divisible by x
Task
Given integers x and y which are both at least 2, find the smallest positive number whose y-th power is divisible by x.
Example
Given x=96 and y=2, the output should be 24 since 24 is the smallest positive n satisfying n^2 is divisible by 96.
Testcases
x  y output
26 2 26
96 2 24
32 3 4
64 9 2
27 3 3

Scoring
This is code-golf. Solution with lowest byte-count wins.
References

y=2: OEIS A019554
y=3: OEIS A019555
y=4: OEIS A053166
y=5: OEIS A015052
y=6: OEIS A015054

Related.

Will X always be greater than Y?

@Fatalize What has that got to do with anything?

There is no test case where X is less than Y, and it can reduce the length of some answers (at least mine) if X is always greater than Y. I would rather have that X can be either bigger or smaller, but then one test case for the latter would be great.

Your references list is the best illustration I've seen of the ridiculous arbitrariness of OEIS entry ordering.

Brachylog, 19 17 16 15 12 bytes
2 bytes saved thanks to @LeakyNun.
:[I:1]*$r=#>

Try it online!
Explanation
               Input = [X, Y]
:[I:1]*        Get a list [X*I, Y] (I being any integer at this point)
       $r=     Get the first integer which is the Yth root of X*I
          #>   This integer must be strictly positive
               This integer is the Output

1 byte off

@LeakyNun Thanks. This will be much slower though.

Why will this be slower?

Slower still, but another byte off

@LeakyNun Because it will try all integers from 1 up to the answer. whereas my answer would propagate the constraints before assigning a value.

To quote the famous Fatalize: "don't care about complexity"

Jelly, 6 bytes
ÆE÷ĊÆẸ

Try it online! or verify all test cases.
How it works
ÆE÷ĊÆẸ  Main link. Arguments: x, y

ÆE      Yield the exponents of x's prime factorization.
  ÷     Divide them by y.
   Ċ    Ceil; round the quotients up to the nearest integer.
    ÆẸ  Return the integer with that exponents in its prime factorization.

R*%⁸i0 is also 6 bytes.

I think that warrants a separate answer.

JavaScript (ES7), 32 bytes
f=(x,y,i=1)=>i**y%x?f(x,y,i+1):i

You never defined f.  I think you need to assign the function to f.

@kamoroso94 Sorry, I'm forever doing that.

Python 3, 60 43 39 bytes
Thanks to @LeakyNun and @Sp3000 for help
f=lambda x,y,i=1:i**y%x<1or-~f(x,y,i+1)

A function that takes input via argument and returns the output.
How it works
The function uses recursion to repeatedly check integers i, starting with i=1, until one satisfying the required condition, here i**y%x<1, is found. This is achieved by taking the logical or of the condition and the result of the expression for i+1 incremented, which here is -~f(x,y,i+1). This expression continuously evaluates as False until a satisfying value j is found, at which point it evaluates to True and recursion stops. Since these are respectively equivalent to 0 and 1 in Python, and the function has repeatedly been adding 1 via the incrementing part, the function returns (j-1)*False + True + (j-1)*1 = (j-1)*0 + 1 + (j-1)*1 = 1 + j-1 = j, as required.
Try it on Ideone

def f(x,y,i=1):¶ while i**y%x:i+=1¶ print(i)

@LeakyNun Thanks. I just thought of a slightly shorter way to do it (43 vs 44) with recursion.

39: f=lambda x,y,z=1:z**y%x<1or-~f(x,y,z+1)

@Sp3000 Doesn't your function return True instead of z?

@LeakyNun You're missing the -~ part, but yes it would return True if x was 1.

Since this function only works if it's assigned to the variable f, shouldn't that assignment be included in the byte count? Or are those bytes freebies?

@Jordan The 39 count includes the f=

Jelly, 6 bytes
R*%⁸i0

Try it online! or verify all test cases.
How it works
R*%⁸i0  Main link. Arguments: x, y

R       Yield range from 1 to x inclusive.
 *      Raise each to power y.
  %⁸    Take modulo of each with base x.
    i0  Find the 1-based index of the first
        occurence of zero, returns.

Haskell, 31 bytes
x#y=[n|n<-[1..],mod(n^y)x<1]!!0

Usage example: 96#2 -> 24.
Direct implementation: try all integers n, keep those that meet the condition and pick the first one.

Also 31: x#y=until(\n->mod(n^y)x<1)(+1)0

05AB1E (10 bytes)
>GN²m¹ÖiNq

Try it online

> Reads the first argument, increments it, and pushes it on the stack
G pops the stack (a) and starts a loop that contains the rest of the program where N takes on the value 1, 2, ... a - 1.
N²m pushes N and the second entry from the input history, then pops them both and pushes the first to the power of the second.
¹ pushes the first entry from the input history onto the stack.
Ö pops the previous two stack entries, then pushes a % b == 0 on the stack.
i pops that from the stack. If true, it executes the rest of the program; otherwise, the loop continues.
N pushes N on the stack.
q terminates the program.

When the program terminates, the top value of the stack is printed.

Please post an explanation of how this code works for those nto familiar with your language, but otherwise good job, and nice first post.

That link seems interesting.

Very nice first answer.

MATL, 9 bytes
y:w^w\&X<

Try it online!
Explanation
y       % Take x and y implicitly. Push x again
        % STACK: x, y, x
:       % Range from 1 to x
        % STACK: x, y, [1, 2, ..., x]
w       % Swap
        % STACK: x, [1, 2, ..., x], y
^       % Power, element-wise
        % STACK: x, [1^y,  2^y, ..., x^y]
w       % Swap
        % STACK: [1^y, 2^y, ..., x^y], x
\       % Modulo, element-wise
        % STACK: [mod(1^y,x), mod(2^y,x), ..., mod(x^y,x)]
        % A 0 at the k-th entry indicates that x^y is divisible by x. The last entry
        % is guaranteed to be 0
&X<     % Arg min: get (1-based) index of the first minimum (the first zero), say n
        % STACK: n
        % Implicitly display

Stack manipulation much.

Yep. I suspect Jelly will have a big advantage here, since it avoids all those "copy" and "swap"

Don't you have find?

@LeakyNun Yes, f, but that finds all nonzero indices. So it would have to be ~f1):  negatve, find, get the first entry

Actually, 12 11 bytes
Many thanks to Leaky Nun for his many suggestions. Golfing suggestions welcome. Try it online!
;)R♀ⁿ♀%0@íu

Original 12-byte approach. Try it online!
1WX│1╖╜ⁿ%WX╜

Another 12-byte approach. Try it online!
w┬i)♀/♂K@♀ⁿπ

A 13-byte approach. Try it online!
k╗2`╜iaⁿ%Y`╓N

Ungolfing:
First algorithm
       Implicitly pushes y, then x.
;      Duplicate x.
)      Rotate duplicate x to bottom of the stack.
R      Range [1, x] (inclusive).
♀ⁿ     Map a**y over the range.
♀%     Map a**y%x over the range.
0@í    new_list.index(0)
u      Increment and print implicitly at the end of the program.

Original algorithm
       Implicitly pushes x, then y.
1WX    Pushes a truthy value to be immediately discarded
         (in future loops, we discard a**y%x)
|      Duplicates entire stack.
         Stack: [y x y x]
1╖     Increment register 0.
╜      Push register 0. Call it a.
ⁿ      Take a to the y-th power.
%      Take a**y mod x.
W      If a**y%x == 0, end loop.
X      Discard the modulus.
╜      Push register 0 as output.

Third algorithm
       Implicitly pushes y, then x.
w      Pushes the full prime factorization of x.
┬      Transposes the factorization (separating primes from exponents)
i      Flatten (into two separate lists of primes and exponents).
)      Rotate primes to the bottom of the stack.
♀/     Map divide over the exponents.
♂K     Map ceil() over all of the divided exponents.
@      Swap primes and modified exponents.
♀ⁿ     Map each prime ** each exponent.
π      Product of that list. Print implicitly at the end of the program.

Fourth algorithm
     Implicitly pushes x, then y.
k╗   Turns stack [x y] into a list [x, y] and saves to register 0.
2    Pushes 2.
  `    Starts function with a.
  ╜i   Pushes register 0 and flattens. Stack: [x y a]
  a    Inverts the stack. Stack: [a y x]
  ⁿ%   Gets a**y%x.
  Y    Logical negate (if a**y is divisible by x, then 1, else 0)
  `    End function.
╓    Push first (2) values where f(x) is truthy, starting with f(0).
N    As f(0) is always truthy, get the second value.
     Print implicitly at the end of the program.

@LeakyNun Waiting for one of your winning golf suggestions :D

@LeakyNun I'd be happy to post those approaches, too, unless you want to post them yourself.

+1 for the smirk ;)

dc, 23 22 bytes
Thanks to Delioth for his tip about input methods, saving a byte
sysxz[zdlylx|0<F]dsFxp

Uses the stack depth operator z for incrementing the test case directly on the stack, and the modular exponentiation operator | for, well, modular exponentiation. Repeat testing until remainder is not greater than zero.

You technically don't need the ? at the beginning, as a standard way to invoke some things is > echo "x y [program]"|dc, where x and y are the same as the Question- x and y will be dropped onto the stack as normal.

@Delioth Interesting, thanks! I always just used the -e option, but I'll use that from now on.

@Delioth, for me, using quotes throws errors reminding me that " is not implemented in dc, while not using quotes obviously gives shell errors. Is there anything to be done about this? I know stderr can be ignored, but it still bothers me.

R, 61 bytes, 39 bytes, 37 bytes, 34 bytes
I'm still a newbie in R programming and it turns out this is my first function I create in R (Yay!) so I believe there's still room for improvement.
function(x,y){for(n in 2:x){if(n^y%%x==0){cat(x,y,n);break}}}

Online test can be conducted here: RStudio on rollApp.

Major progress:
function(x,y){which.max((1:x)^y%%x==0)}

which.max works because it returns the highest value in a vector and if there are multiple it will return the first. In this case, we have a vector of many FALSEs (which are 0s) and a few TRUEs (which are 1s), so it will return the first TRUE.

Another progress:
function(x,y)which.max((1:x)^y%%x==0)

Finally, it beats out the answer using Python by two bytes. :)
Another progress: (Again!)
function(x,y)which.min((1:x)^y%%x)

Many thanks to Axeman and user5957401 for the help.

I think that your test link is dead.

@TheBikingViking Thanks for pointing that out. I'll edit it after having my late lunch

if you use which.min, you could get rid of the ==0. The modulus will return a number, which be no lower than 0.

@user5957401 Edited.Bolshoe spasibo...

For the same length of 34 bytes you also had the similar function(x,y)which(!(1:x)^y%%x)[1].

Post it as an answer then @plannapus :)

05AB1E, 8 bytes
Lsm¹%0k>

Explanation
L         # range(1,x) inclusive
 sm       # each to the power of y
   ¹%     # each mod x
     0k   # find first index of 0 (0-based)
       >  # increment to 1-based

Try it online

Perl 6,  26  25 bytes
{first * **$^y%%$^x,1..$x}
{first * **$^y%%$^x,1..*}
Explanation:
# bare block with two placeholder parameters ｢$^y｣ and ｢$^x｣
{
  # find the first value
  first

  # where when it ｢*｣ is taken to the power
  # of the outer blocks first parameter ｢$^y｣
  * ** $^y
  # is divisible by the outer blocks second parameter ｢$^x｣
  %% $^x,

  # out of the values from 1 to Inf
  1 .. *
}

Mathematica, 36 bytes
(i=1;While[n=i++;Mod[n^#2,#]!=0];n)&

Dyalog APL, 11 bytes
Translation of this.
0⍳⍨⊣|(⍳⊣)*⊢

0⍳⍨ find the first zero in
⊣| the division remainders when x divides
(⍳⊣)* the integers one through x, raised to the power of
⊢ y
TryAPL online!

Perl, 29 26 bytes
Includes +3 for -p (not +1 since the code contains ')
Run with the input on STDIN
power.pl <<< "96 2"

power.pl:
#!/usr/bin/perl -p
/ /;1while++$\**$'%$`}{

PowerShell v2+, 48 bytes
param($x,$y)(1..$x|?{!(("$_*"*$y+1|iex)%$x)})[0]

Takes input $x and $y. Constructs a range from 1 to $x, then uses Where-Object to filter those numbers. The filter takes the string "$_*" (i.e., the current number with an asterisk) and uses string-multiplication to concatenate those $y times, then tacks on a final 1 at the end, then pipes that to iex (short for Invoke-Expression and similar to eval). This takes the place of [math]::Pow($_,$y), since PowerShell doesn't have an exponentiation operator, and is two bytes shorter. That's fed into the modulo operator % with $x -- thus, if it's divisible, this will be 0, so we encapsulate that in parens and take the Boolean-not !(...) thereof. Thus, if its divisible, it'll be included by this filter, and all other numbers will be excluded.
Finally, we encapsulate the resultant numbers in parens (...) and take the [0] index. Since the range entered sorted 1..$x, this will be the smallest. That's left on the pipeline and printing is implicit.
Test cases
PS C:\Tools\Scripts\golfing> (26,2),(96,2),(32,3),(64,9),(27,3)|%{($_-join', ')+' -> '+(.\smallest-positive-number-divisor.ps1 $_[0] $_[1])}
26, 2 -> 26
96, 2 -> 24
32, 3 -> 4
64, 9 -> 2
27, 3 -> 3

PHP, 55 33 bytes
$i=1;while($i**$y%$x)$i++;echo$i;

Pyth, 9 bytes
AQf!%^THG

A program that takes input of a list of the form [x, y] on STDIN and prints the result.
Try it online
How it works
AQf!%^THG  Program. Input: Q
AQ         G=Q[0];H=Q[1]
  f        First truthy input T in [1, 2, 3, ...] with function:
     ^TH    T^H
    %   G   %G
   !        Logical not (0 -> True, all other modulus results -> False)
           Implicitly print

PHP 59 bytes
Sorry, but I can't test this from my mobile. :)
function blahblah($x,$y){
  for($i=0;1;$i++){
    if(!$i^$y%$x){
      return $i;
    }
  }
}

Golfed
function b($x,$y){for($i=0;1;$i++){if(!$i^$y%$x)return $i;}

You're using $z where you should be using $x and I don't think you're incrementing $i in the loop

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Staggered Starts
In races in which racers go around at least one turn of a curved track, the starting positions for each racer are staggered, so that each racer travels the same distance around the track (otherwise, the racer in the innermost lane would have a huge advantage).
Given the lengths of the major and minor axes (or semi-major and semi-minor, if you'd prefer) of an elliptical track and the number of lanes in the track, output the distances from the innermost lane's starting point that each lane should be staggered.
Specifications

Each lane is an ellipse with semi-major axes 5 units longer than the next-shortest lane. For simplicity, assume that the lanes have 0 width.
The innermost lane always starts at 0, and every other starting point is a positive integer greater than or equal to the previous starting point.
Input and output may be in any convenient and reasonable format.
The inputs will always be integers.
You must calculate the circumference of the track to within 0.01 units of the actual value.
Outputs are to be rounded down to the nearest integer (floored).
The finish line is the starting point for the innermost racer. There is only one lap in the race.
The lengths of the axes are measured using the innermost lane of the track.
Outputting the 0 for the innermost lane's offset is optional.

Test Cases
Format: a, b, n -> <list of offsets, excluding innermost lane>
20, 10, 5 -> 30, 61, 92, 124
5, 5, 2 -> 31
15, 40, 7 -> 29, 60, 91, 121, 152, 183
35, 40, 4 -> 31, 62, 94

These test cases were generated with the following Python 3 script, which uses an approximation of the circumference of an ellipse devised by Ramanujan:
#!/usr/bin/env python3

import math

a = 35 # semi-major axis
b = 40 # semi-minor axis
n = 4  # number of lanes
w = 5  # spacing between lanes (constant)

h = lambda a,b:(a-b)**2/(a+b)**2
lane_lengths = [math.pi*(a+b+w*i*2)*(1+3*h(a+w*i,b+w*i)/(10+math.sqrt(4-3*h(a+w*i,b+w*i)))) for i in range(n)]

print("{}, {}, {} -> {}".format(a, b, n, ', '.join([str(int(x-lane_lengths[0])) for x in lane_lengths[1:]])))

The approximation used is:

Finally, here is a helpful diagram for understanding the calculations of the offsets:

I use Ramanujan's approximation like you did. Is that what we're supposed to do, or do you want us to evaluate the convergence of the infinite series?

@Adám You can do whatever it takes to get the required precision. The Ramanujan approximation is good for many values because its error is on the order of h**5, which is well under 0.01 for a wide range of values.

What good is a minimum accuracy when there is no bound on the input size?

05AB1E, 43 bytes
UVFXY-nXY+WZn/3*©T4®-t+/>Z*žq*5DX+UY+V})¬-ï

Explanation
UV                                           # X = a, Y = b
  F                                   }      # n times do
   XY-n                                      # (a-b)^2
       XY+W                                  # Z = (a + b)
             /                               # divide (a-b)^2
           Zn                                # by (a+b)^2
              3*                             # multiply by 3
                ©                            # C = 3h
                       /                     # 3h divided by
                 T                           # 10
                      +                      # +
                  4®-t                       # sqrt(4-3h)
                        >                    # increment
                         Z*žq*               # times (a + b)*pi
                              5DX+UY+V       # increase a and b by 5
                                       )     # wrap in list of circumferences
                                        ¬-   # divide by inner circumference
                                          ï  # floor
                                             # implicitly display

Try it online!

Haskell, 103 98 bytes
c!d|h<-3*d*d/c/c=pi*c*(1+h/(10+sqrt(4-h)))
f a b n|x<-a-b=[floor$(a+b+10*w)!x-(a+b)!x|w<-[1..n-1]]

Dyalog APL, 45 bytes
Prompts for n, then for a b. Requires ⎕IO←0 which is default on many systems.
⌊1↓(⊢-⊃)(○+×1+h÷10+.5*⍨4-h←3×2*⍨-÷+)⌿⎕∘.+5×⍳⎕

⍳⎕ prompt for n, then give {0, 1, 2, ..., n−1)
5× multiply by five to get {0, 5, 10, ..., 5n−5}
⎕∘.+ prompt for a and b, then make an addition table:
  a, a+5, a+10, ... a+5n−5
  b, b+5, b+10, ... b+5n−5
(...)⌿ apply the parenthesised function to each vertical pair, i.e.
  f(a, b), f(a+5, b+5), f(a+10, b+10), ..., f(a+5n−5, b+5n−5)
  where f(x, y) is*

○ pi times
+× (x + y) times
1+ one plus
h÷ h(x, y) [the function h will be defined later] divided by
10+ ten plus
.5*⍨ the square-root of
4- four minus
h← h(x, y), which is
3× three times
2*⍨ the square of
-÷ (x − y) divided by
+ x + y

(⊢-⊃) on the result of the function applied to each pair, subtract the value of the first result
1↓ remove the first (zero)
⌊ round down
TryAPL online!

*In procedural language:
-÷+ find the fraction of the difference between and the sum of x and y
2*⍨ square that fraction
3× multiply that square by three
h← assign that product to h
4- subtract that product from four
.5*⍨ take the square-root of that difference
10+ add ten to that square-root
h÷ divide h by that sum
1+ add one to that fraction
+× multiply that sum with the sum of x and y
○ multiply that product by pi

Python 3, 168 164 bytes
Thanks to @Adám and @Mego for -2 bytes each
from math import*
h=lambda a,b:3*(a-b)**2/(a+b)**2;C=lambda a,b:pi*(a+b)*(1+h(a,b)/(10+sqrt(4-h(a,b))))
f=lambda a,b,n:[int(C(a+i*5,b+i*5)-C(a,b))for i in range(n)]

A function f that takes input via argument and returns a list of lane offsets, including 0 for the innermost lane.
How it works
This uses Ramanujan's approxiamtion. We simply define functions h and C for calculating the parameter and circumference, then subtract the length of the innermost lane from the length of the current lane and floor, for all lanes.
Try it on Ideone

sqrt(4-3*h(a,b)) is shorter as (4-3*h(a,b))**.5, and floor can be replaced by int. Doing both of those means you don't need to import math.

@Mego Thanks. Unless I'm being stupid, aren't those first two the same length? However, if the import statement gets removed, there is then the problem of defining pi.

By including the the 3* in h, you should save two bytes.

I totally missed that you use pi You might be able to hardcode it with enough precision. And yeah, the first two are the same length - I meant without the import, of course! :P

@Adám Thanks for pointing that out.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/