Watch the video at this link: https://curiosity.com/videos/6174-numberphile-numb
ID: 3919960 • Letter: W
Question
Watch the video at this link: https://curiosity.com/videos/6174-numberphile-numberphile/. Then download the Matlab file Kaprekars_operation.m. Test this file with a few random four digit numbers. Note that this script won’t work for values less than 1000.
a. Change this file to be a function file that would receive one input of four digits number and would output two values - Output 1: the number the operation reaches (should be Kaprekar’s constant); Output 2: the number of iterations it took to reach that number. You do not need to submit the function file, but you will need it for your own reference in part b.
b. Write a script that tests the Kaprekar’s theory for initial values between 1000 and 9998 except for the values 1111, 2222, 3333, ...., 8888. Your script should print the
following:
i. Count of how many initial values were tested.
ii. Count of how many values returned Kaprekar’s number 6174.
iii. How many of these values took 1 iteration to reach Kaprekar’s number, along with how many took 2 iterations, 3 iterations, 4 iterations, 5 iterations, 6 iterations, 7 iterations, and more than 8 iterations.
Self-check: for (ii), all values should return 6174. For (iii), all values should take less than 8 iterations.
Kaprekars_operation.m file:
%% Kaprekar's operation (Magic Number Example) Script.
% Watch this video for more explination of the problem:
https://curiosity.com/videos/6174-numberphile-numberphile/
%This script will request the user input a 4-digit number (not all the
%same digit) and from this number will perform calculations to compute the
%constant number 6174 which always follows from the given algorithm.
%Script author: Cody Scharzenberger
%Clear Everything.
clear
close all
clc
%% Request User Input & Verify its Validity.
%Create a boolean variable to store whether the input is valid.
bValidInput = false;
%While the input is not valid, continue asking for user input...
while ~bValidInput
%Request user input.
x = input('Enter a 4 Digit Number (Not All the Same Digit): x = ');
%%% Create an array of the digits of the given number.
%Turn the number into a character array.
xstr = num2str(x);
%Preallocate a variable for storing the digits.
x_digits = zeros(1,length(xstr));
%Store the digits into an array. This will be used to check that not
%all of the digits are the same.
for k = 1:length(xstr)
x_digits(k) = str2double(xstr(k));
end
%%% Determine whether the input is valid.
%(1) Input must have 4 digits,
%(2) Input must not be a single digit repeated four times.
if (length(x_digits) ~= 4) || (sum(x_digits == x_digits(1)) == 4)
fprintf('Invalid Number. Try Again. ')
else
bValidInput = true; %Flag that a valid input has been given.
end
end
%% Perform Algorithm to Compute 6174 from User Input.
%%% Preallocate for a while loop.
%Create a variable to store the values produced by the algorithm.
xs(1) = x; %Set the first value to be the original user input.
%Create a loop variable to determine the number of loop interations.
k = 0;
%Create a boolean flag variable to determine when the algorithm is
%producing the same result.
bMatchFound = false;
%%% Use a while loop to perform the computation.
%Conitnue iterating until the algorithm is producing the same number...
while ~bMatchFound
%Add to the loop variable.
k = k + 1;
%Convert the current number to a string.
xstr = num2str(x);
%Need to add leading zeros if our value has fewer than 4 digits...
xstr = [num2str(zeros(1,4-length(xstr))), xstr]; %IF YOU DON'T HAVE
THIS LINE, SCRIPT WON'T WORK WHEN THE NUMBER HAS THREE REPEATED DIGITS.
%Sort the string into ascending & descending arrays.
xstr_ascend = sort(xstr, 'ascend');
xstr_descend = sort(xstr, 'descend');
%Turn these strings back into double arrays.
x_ascend = str2double(xstr_ascend);
x_descend = str2double(xstr_descend);
%Find the different between these two numbers.
x = x_descend - x_ascend;
%Store this new value into the array tracking the sequence of numbers
%produced by this algorithm.
xs(k+1) = x;
%Check to see if a match has been found. ie, is this number the same
%as the one produced on the previous iteration?
if xs(k) == xs(k+1)
bMatchFound = true; %Switch the flag variable.
end
end
%Compute the number of iterations that were performed.
n = k - 1;
%% Print out the Results.
fprintf(' ')
fprintf('Number of Iterations: n = %0.0f [#] ', n)
fprintf('Magic Sequence: ')
disp(xs(1:end-1))
Explanation / Answer
Here is the required MATLAB Code (Explanation in Comments) -
Kaprekars_operation.m (function) -
function [num_reached, num_ops] = Kaprekars_operation(number)
%% Kaprekar's operation (Magic Number Example) Script.
% Watch this video for more explination of the problem:
% https://curiosity.com/videos/6174-numberphile-numberphile/
%This script will request the user input a 4-digit number (not all the
%same digit) and from this number will perform calculations to compute the
%constant number 6174 which always follows from the given algorithm.
%Script author: Cody Scharzenberger
%Clear Everything.
%% Request User Input & Verify its Validity.
%Create a boolean variable to store whether the input is valid.
bValidInput = false;
%While the input is not valid, continue asking for user input...
while ~bValidInput
x = number;
%%% Create an array of the digits of the given number.
%Turn the number into a character array.
xstr = num2str(x);
%Preallocate a variable for storing the digits.
x_digits = zeros(1,length(xstr));
%Store the digits into an array. This will be used to check that not
%all of the digits are the same.
for k = 1:length(xstr)
x_digits(k) = str2double(xstr(k));
end
%%% Determine whether the input is valid.
%(1) Input must have 4 digits,
%(2) Input must not be a single digit repeated four times.
if (length(x_digits) ~= 4) || (sum(x_digits == x_digits(1)) == 4)
fprintf('Invalid Number. Try Again. ')
return
else
bValidInput = true; %Flag that a valid input has been given.
end
end
%% Perform Algorithm to Compute 6174 from Function Input.
%%% Preallocate for a while loop.
%Create a variable to store the values produced by the algorithm.
xs(1) = x; %Set the first value to be the original user input.
%Create a loop variable to determine the number of loop interations.
k = 0;
%Create a boolean flag variable to determine when the algorithm is
%producing the same result.
bMatchFound = false;
%%% Use a while loop to perform the computation.
%Conitnue iterating until the algorithm is producing the same number...
while ~bMatchFound
%Add to the loop variable.
k = k + 1;
%Convert the current number to a string.
xstr = num2str(x);
%Need to add leading zeros if our value has fewer than 4 digits...
xstr = [num2str(zeros(1,4-length(xstr))), xstr]; %IF YOU DON'T HAVE
% THIS LINE, SCRIPT WON'T WORK WHEN THE NUMBER HAS THREE REPEATED DIGITS.
%Sort the string into ascending & descending arrays.
xstr_ascend = sort(xstr, 'ascend');
xstr_descend = sort(xstr, 'descend');
%Turn these strings back into double arrays.
x_ascend = str2double(xstr_ascend);
x_descend = str2double(xstr_descend);
%Find the different between these two numbers.
x = x_descend - x_ascend;
%Store this new value into the array tracking the sequence of numbers
%produced by this algorithm.
xs(k+1) = x;
%Check to see if a match has been found. ie, is this number the same
%as the one produced on the previous iteration?
if xs(k) == xs(k+1)
bMatchFound = true; %Switch the flag variable.
end
end
%Compute the number of iterations that were performed.
n = k-1;
%% Store the Results for Returning
num_ops = n; % Number of Operations required
num_reached = x; % Number Reached
end
----------
script.m (script to print the required results)
% Generate the list of numbers from 1000-9998 except 1111,2222,...
numbers = 1000:9998;
numbers([112,1223,2334,3445,4556,5667,6778,7889]) = [];
% Initalize Results
num_values_tested = 0; % Initialize Number of Values tested
num_values_return_6174 = 0; % Initialize Number of Values that returned 6174
num_values_iters = zeros(1, 8); % Initialize Number of Values that took 1,2,..,8+ iterations
% Loop through all the values and update the results
for i = 1:length(numbers)
[value, num_ops] = Kaprekars_operation(numbers(i)); % Perform Kaprekar's operation on number
num_values_tested = num_values_tested+1; % Update number of values tested
if value == 6174
% If the value returned is indeed 6174
num_values_return_6174 = num_values_return_6174 + 1; % Update number of values that return 6174
% Update the number of iterations it took in the counter
if num_ops > 8
num_ops = 8; % The eighth position stores both 8 and more than 8 iterations
end
if num_ops == 0
continue; % Number of Operations is 0 for the number 6174
end
num_values_iters(num_ops) = num_values_iters(num_ops) + 1; % Update the count
end
end
% Print the Results
fprintf("Number of Values tested: %d ", num_values_tested);
fprintf("Number of Values returned Kaprekar's Number 6174: %d ", num_values_return_6174);
fprintf("Number of Iterations Required: ");
for j = 1:length(num_values_iters)
fprintf("%d: %d ", j, num_values_iters(j));
end
--------
Here is the output that I got -
Number of Values tested: 8991
Number of Values returned Kaprekar's Number 6174: 8991
Number of Iterations Required:
1: 356
2: 519
3: 2124
4: 1124
5: 1379
6: 1508
7: 1980
8: 0
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.