Smallest_multiple function in MATLAB - algorithm

Hi I am having problems with the following function in Matlab. Can some please help?
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. Write a function called smallest_multiple that returns a uint64, the smallest positive number that is evenly divisible by all of the numbers from 1 to n where n is a positive integer scalar and is the only input argument of the function. If the result would be greater than what can be represented as a uint64, the function returns 0. (Inspired by Project Euler.)
Below is the code I wrote for the function but it gives error
Feedback: Your function made an error for argument(s) 2
Your solution is _not_ correct.
Help please...
function [answer]=smallest_multiple(n)
limit = 1e10;
N = 20;
for i = N:N:limit
for j = N:-1:1
if mod(i,j) ~= 0
break
end
end
if j == 1
answer = i;
break
end
end
fprintf('The smallest evenly divisible number is %.0d\n',answer)

Your function looks correct. However the argument you pass is a lowercase n instead of an uppercase N, which you use during your code.
So the correct function (with limit as argument) is
function [answer]=smallest_multiple(N,limit)
for i = N:N:limit
for j = N:-1:1
if mod(i,j) ~= 0
break
end
end
if j == 1
answer = i;
break
end
end
fprintf('The smallest evenly divisible number is %.0d\n',answer)

Related

Algorithm to sum up all digits of a number

Can you please explain to me how this loop works? What is going on after first loop and after second etc.
def sum(n):
s = 0
while n:
s += n % 10
n /= 10
return s
>>> print sum(123)
6
def sum(n):
s = 0
while n:
s += n % 10
n /= 10
return s
Better rewrite this way (easier to understand):
def sum(n):
s = 0 // start with s = 0
while n > 0: // while our number is bigger than 0
s += n % 10 // add the last digit to s, for example 54%10 = 4
n /= 10 // integer division = just removing last digit, for example 54/10 = 5
return s // return the result
n > 0 in Python can be simply written as n
but I think it is bad practice for beginners
so basically, what we are doing in this algorithm is that we are taking one digit at a time from least significant digit of the number and adding that in our s (which is sum variable), and once we have added the least significant digit, we are then removing it and doing the above thing again and again till the numbers remains to be zero, so how do we know the least significant digit, well just take the remainder of the n by dividing it with 10, now how do we remove the last digit(least significant digit) , we just divide it with 10, so here you go, let me know if it is not understandable.
int main()
{
int t;
cin>>t;
cout<<floor(log10(t)+1);
return 0;
}
Output
254
3

Check a valid credit card number using python

This is a homework assignment that I've been working on to compute if a credit card number is valid. It has many steps and uses 2 other helper functions.
The first helper function makes a list consisting of each digit in n:
def intToList(n):
strr = [num for num in str(n)]
theList = list(map(int, strr))
return theList
The second helper function adds the sum of digits in a number. For example:
def addDigits(n):
sums = 0
while n:
if n > 0:
sums += n % 10
n //= 10
else:
return
return sums
>>>(332) #(3+3+2) = 7
>>> 7
So the function I am working on is suppose to validate a 16 digit credit card number. It has specific orders to follow in the order given.
Verifies that it contains only digits. #Done.
Verifies that it is 16 digits long. #Done.
if n is a string, it converts it to an integer.
creates a list using the function intToList(n).
Multiplies the odd indices of the list made by intToList(n) by 2 and any products that produce two-digit numbers are replaced by the sum of the digits using the function addDigits(n).
Computes the sum of all the single digits in the list made my intToList(n). If the sum is equal to 0 modulo 10, the original value, n, is a valid credit card number.
As of right now I have this:
def checkCreditCard(n):
#Suppose to convert n to int.
n = int(n)
#Helper function 1 to make a list.
myList = intToList(n)
#For loop to apply the math to each odd indices.*
for ele in myList:
if ele % 2 == 1:
ele *= 2
if ele >= 10:
single = addDigits(?) #not sure what to put I've tried everything
if sum(myList) % 10 == 0:
return True
return False
Here is my issue, I am unsure where to go from here. I am pretty sure the code above is correct so far, but I don't know how to make the products that produce two-digit numbers compute to single digit ones using my function and computes the sum of all the single digits in the list.
Any help would be greatly appreciated. Let me know if I can clear anything up.
added what I've worked on.
Simple trick: The sum of the digits of all numbers from 10 to 18 (the possible two digit values for doubling or adding single digit values) can be computed simply by subtracting 9. So if you have a possible single, possibly double digit value, you can use it as a single digit with:
singledigit = maybetwodigit - 9 * (maybetwodigit >= 10)
For the record, your code as written is not correct:
def checkCreditCard(n):
#My checks for length and digits.
if len(str(n)) == 16 and str(n).isdigit():
return True
else:
return False
# nothing at this line or below will ever execute, because both your if
# and else conditions return
Also, your (currently unused) loop will never work, because you don't assign what you've calculated. You probably want something like this:
for i, ele in enumerate(myList):
if i % 2 == 1:
ele *= 2
myList[i] = ele - 9 * (ele >= 10) # Seamlessly sum digits of two digit nums

Random choosing number in array without repeated

I have a algorithm to randomly select element t in a array with out repeated. This is more detail of algorithm
It can explain as folowing:
Initial a array index u that stores the index of numbers from 1 to k (line 1 to 3)
Set initial of gamma from k and reduce by one for each iteration. The purpose of gamma is for without repeated (line 4,9,10)
Random choose a number t from 1 to N(at the j=1, choose 1 to k, N are nonrepated number), and then put the number to the end of array.
Repate the step 2 to 3
If gamma =0,reset gamma=k
This function will return the t.
For example, I have a array A=[1,2,3,4,5,6,7,8,9], k=9 =size(A), N=12 (From 1 to 9, number select only one time). Now I want to use this algorithm to randomly select number t from array A. This is my code. However, it does not similar the line 6 in the algorithm. Is it right? Let see my code help me
function nonRepeat
k=9;
u=1:k; % initial value of index
N=12
gamma=k;
for j=1:N
index=randi(gamma,1); % use other choosing
t=u(index)
%%swapping
temp=u(t);
u(t)=u(gamma);
u(gamma)=temp;
gamma=gamma-1;
if gamma==0
gamma=k;
end
end
end
I think index=randi(gamma,1); is not right because it says select number t randomly but you select index randomly and assign t=u(index).
See if it works,
k = 9;
u = 1 : k;
N = 12;
gamma = k;
for j = 1 : N
t = randi(gamma,1);
temp = u(t);
u(t) = u(gamma);
u(gamma) = temp;
gamma = gamma - 1;
if gamma == 0
gamma = k;
end
end

Prime factoring returns nil when fed primes

I made a method that generates prime factors. Whatever composite number I push to it, it gives the prime factors. However, if I push a prime number into it, it wouldn't return 1 and the number itself. Instead, it would return 1 and some prime number smaller than the number pushed into the method.
I decided to shove an if statement that would cut the process short if the number pushed into turns out to be prime. Here's the code:
def get_prime_factors(number)
prime_factors = []
i = 0
primes = primes_gen(number)
if primes.include?(number)
return "Already a prime!"
end
original_number = number
while primes[i] <= original_number / 2
if number % primes[i] == 0
prime_factors << primes[i]
number = number / primes[i]
else
i = i + 1
end
if number == 1
return prime_factors
end
end
end
I fed 101 to the method and the method returned nil. This method calls the primes_gen method, which returns an array containing all primes smaller than the input value. Here it is:
def primes_gen(limit)
primes = []
i = 0
while i <= limit
primes << i if isprime?(i)
i = i + 1
end
primes.delete(0)
primes.delete(1)
return primes
end
I know there ought to be a more finessed way to fix the. If anyone wants to recommend a direction for me to explore as far as that goes, I'd be very grateful.
EDIT: Changed line 4 of the primes_gen() method to include a <= operator instead of a < operator.
Try changing primes = primes_gen(number) to primes = primes_gen(number+1) in first function and see if it works. Or try changing the i < limit condition to i <= limit in the second function.
Also, why are you deleting the 0th and 1st element in primes_gen method? Is it because of values you get for 0, 1? In which case, you can initialize with i=2.

how do I start this pseudocode

ok I am lost right now by this assignment and just need some help.
The assignment is Design a program that generates the sum of numbers.
Given a number (user input) you need an application that will produce a sum of the numbers from 1 to that given number I just need some help to start because I am just having to hard of a time and i know it might seem easy but never had any experience to any of this at all.
var input = getUserInput;
var sum;
while (input > 0)
{
sum = sum + input--;
}
print sum;
You can start with something as straightforward as this:
input = getuserInput()
count = 0
sum = 0
while count < input:
count = count + 1
sum = sum + count
return sum
...then enhance it.
INPUT number
VARIABLE sum = 0
FOR VARIABLE n = 1 TO number WITH STEP 1 DO
sum += n
END FOR
PRINT sum
Translated to lua it would look like this:
number = tonumber( io.read() )
sum = 0
for n = 1, number, 1 do
sum = sum + n
end
print(sum)
Translated into python it would look like
Number = int(input("Number:"))
Sum = 0
for n in range(1,Number+1):
Sum += n
print(Sum)
Though the pythonic way would resemble:
number = int(input("Number:"))
print(sum(range(number+1)))
When applying this to any language look out for the following:
Converting the user's input to an integer, by default it will normally be a string i.e "...".
Declare a variable to hold the total (in our case sum) before you try to add a number to it i.e n.
Make sure your for loop goes from 1 to number

Resources