Palindromic Wing Primes - Mathematica - numbers

definition :
Palindromic Wing Primes (or PWP's for short) are numbers that
are primes, palindromic in base 10, and consisting of one central digit
surrounded by two wings having an equal amount of identical digits and
different from the central one. E.g.
101
99999199999
333333313333333
7777777777772777777777777
11111111111111111111111111111111411111111111111111111111111111111
A number is a palindromic wing prime if it is both a palindromic wing and prime. Here are the first several palindromic wing primes:
101, 131, 151, 181, 191, 313, 353, 373, 383, 727, 757, 787, 797, 919, 929, 11311, 11411, 33533, 77377, 77477, 77977, 1114111, 1117111, 3331333, 3337333, 7772777, 7774777, 7778777, 111181111, 111191111, 777767777, 77777677777,...
Please i need help with find the right algorithm or pseudo code for if a number is palindromic wing
and if someone could help me with guid me to more info about the Palindromic Wing Primes , their history and the last results and maybe help me with "mathematica Programming " that would be amazing
kind regards

Testing wing palindromes from wing length 1 to 20 using Mathematica.
sets = DeleteCases[Tuples[Range[0, 9], 2], {a_, a_} | {0, _}];
grow[n_] := Map[Flatten, {a = ConstantArray[#1, n], #2, a} & ### sets]
test[c_] := If[PrimeQ[k = FromDigits#c], AppendTo[output, k]]
run[from_, to_] := Do[test /# grow[i], {i, from, to}]
output = {};
run[1, 20]
101
131
151
181
191
...
111111111111111111131111111111111111111
777777777777777777797777777777777777777
77777777777777777777977777777777777777777

Interesting definition, first time that I hear about that.
Assuming that you know how to check if a number is palindromic and prime, here is some pseudo and python code
isPalindromicWing(N){
if isPalindromic(N){
num <- toString(N)
tam <- length(num)
if isOdd(tam) and lenght(toSet(num)) = 2{
middle <- num[ floor(tam/2) ]
if 1 = num.count(middle){
return True
}
}
}
return False
}
isPWP(N){
return isPalindromicWing(N) and isPrime(N)
}
I use sets to remove repetitions, and as the number can only have 2 different digit with lenght(toSet(num)) == 2 I check for that, then I take the middle number and check if only there is one of it in the number. The rest I think is self explanatory.
in python that is
def isPalindromic(N):
num = str(N)
return N == int( num[::-1] )
def isPalindromicWing(n):
if isPalindromic(n):
num = str(n)
tam = len(num)
if tam % 2 == 1 and len(set(num)) == 2:
middle = num[tam // 2]
if 1 == num.count(middle):
return True
return False
I don't know about "mathematica Programming", but is you understand this code surely you can do it in that too

Related

How to round integer number using precision in flutter

I am trying to make the Y axis intervals of linechart dynamic in flutter. Here the MaxVal will get the maximum value of the Y axis.
int interval = (maxVal/6).toInt();
int length = interval.toString().length.toInt();
So here I have divided the maxVal with 6 so I will get the interval and I will find out the length. Next I need to round the interval according to the length. But I couldn't see any option to add precision for in flutter.
The Expected Output
If maxVal = 10000 then
interval will 1666
then length will 4. Then
I expected rounded value will be 2000
I'm assuming that you're asking to round a (non-negative) integer to its most significant base-10 digit. A general way to round non-negative integers is to add half of the unit you want to round to and to then truncate. For example, if you want to round a non-negative integer to the nearest 1000, you can add 1000/2 = 500, and then discard the hundreds, tens, and ones digits. An easy way to discard those digits is to perform an integer division by 1000 and then to multiply by 1000 again.
The trickiest part is determining what unit you want to round to since that's variable. If you want the most significant base-10 digit, you will need to determine the number of digits. In theory you can compute that with logarithms, but it's usually risky to depend on exact results with floating-point arithmetic, you'd have to deal with 0 as a special case, and it's harder to be confident of correctness. It's simpler and less error-prone to just find the length of the number's string representation. Once we find the number of digits, we can determine which unit to round to computing a corresponding power of 10.
import 'dart:math';
/// Rounds [n] to the nearest multiple of [multiple].
int roundToMultiple(int n, int multiple) {
assert(n >= 0);
assert(multiple > 0);
return (n + (multiple ~/ 2)) ~/ multiple * multiple;
}
/// Rounds [n] to its most significant digit.
int roundToMostSignificantDigit(int n) {
assert(n >= 0);
var numDigits = n.toString().length;
var magnitude = pow(10, numDigits - 1) as int;
return roundToMultiple(n, magnitude);
}
void main() {
var inputs = [
0,
1,
5,
9,
10,
11,
16,
19,
20,
21,
49,
50,
51,
99,
100,
469,
833,
1666,
];
for (var n in inputs) {
var rounded = roundToMostSignificantDigit(n);
print('$n => $rounded');
}
}
which prints:
0 => 0
1 => 1
5 => 5
9 => 9
10 => 10
11 => 10
16 => 20
19 => 20
20 => 20
21 => 20
49 => 50
50 => 50
51 => 50
99 => 100
100 => 100
469 => 500
833 => 800
1666 => 2000
(The above code should be tweakable to handle negative numbers too if desired, but first you would need to define whether negative numbers should be rounded toward 0 or toward negative infinity.)

Prime numbers print from range 2...100

I have been assigned with a task to print prime numbers from a range 2...100. I've managed to get most of the prime numbers but can't figure out how to get rid of 9 and 15, basically multiples of 3 and 5. Please give me your suggestion on how can I fix this.
for n in 2...20 {
if n % 2 == 0 && n < 3{
print(n)
} else if n % 2 == 1 {
print(n)
} else if n % 3 == 0 && n > 6 {
}
}
This what it prints so far:
2
3
5
7
9
11
13
15
17
19
One of effective algorithms to find prime numbers is Sieve of Eratosthenes. It is based on idea that you have sorted array of all numbers in given range and you go from the beginning and you remove all numbers after current number divisible by this number which is prime number. You repeat this until you check last element in the array.
There is my algorithm which should do what I described above:
func primes(upTo rangeEndNumber: Int) -> [Int] {
let firstPrime = 2
guard rangeEndNumber >= firstPrime else {
fatalError("End of range has to be greater than or equal to \(firstPrime)!")
}
var numbers = Array(firstPrime...rangeEndNumber)
// Index of current prime in numbers array, at the beginning it is 0 so number is 2
var currentPrimeIndex = 0
// Check if there is any number left which could be prime
while currentPrimeIndex < numbers.count {
// Number at currentPrimeIndex is next prime
let currentPrime = numbers[currentPrimeIndex]
// Create array with numbers after current prime and remove all that are divisible by this prime
var numbersAfterPrime = numbers.suffix(from: currentPrimeIndex + 1)
numbersAfterPrime.removeAll(where: { $0 % currentPrime == 0 })
// Set numbers as current numbers up to current prime + numbers after prime without numbers divisible by current prime
numbers = numbers.prefix(currentPrimeIndex + 1) + Array(numbersAfterPrime)
// Increase index for current prime
currentPrimeIndex += 1
}
return numbers
}
print(primes(upTo: 100)) // [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
print(primes(upTo: 2)) // [2]
print(primes(upTo: 1)) // Fatal error: End of range has to be greater than or equal to 2!
what is the Prime num : Prime numbers are the positive integers having only two factors, 1 and the integer itself,
//Funtion Call
findPrimeNumberlist(fromNumber: 1, toNumber: 100)
//You can print any range Prime number using this fucntion.
func findPrimeNumberlist(fromNumber:Int, toNumber: Int)
{
for i in fromNumber...toNumber
{
var isPrime = true
if i <= 1 { // number must be positive integer
isPrime = false
}
else if i <= 3 {
isPrime = true
}
else {
for j in 2...i/2 // here i am using loop from 2 to i/2 because it will reduces the iteration.
{
if i%j == 0 { // number must have only 1 factor except 1. so use break: no need to check further
isPrime = false
break
}
}
}
if isPrime {
print(i)
}
}
}
func getPrimeNumbers(rangeOfNum: Int) -> [Int]{
var numArr = [Int]()
var primeNumArr = [Int]()
var currentNum = 0
for i in 0...rangeOfNum{
currentNum = i
var counter = 0
if currentNum > 1{
numArr.append(currentNum)
for j in numArr{
if currentNum % j == 0{
counter += 1
}
}
if counter == 1{
primeNumArr.append(currentNum)
}
}
}
print(primeNumArr)
print(primeNumArr.count)
return primeNumArr
}
Then just call the function with the max limit using this
getPrimeNumbers(rangeOfNum: 100)
What is happening in above code:
The numArr is created to keep track of what numbers have been used
Any number that is prime number is added/appended to primeNumArr
Current number shows the number that is being used at the moment
We start from 0 ... upto our range where we need prime numbers upto (with little modification it can be changed if the range starts from other number beside 0)
Remember, for a number to be Prime it should have 2 divisor means should be only completely divisible by 2 numbers. First is 1 and second is itself. (Completely divisible means having remainder 0)
The counter variable is used to keep count of how many numbers divide the current number being worked on.
Since 1 is only has 1 Divisor itself hence its not a Prime number so we start from number > 1.
First as soon as we get in, we add the current number being checked into the number array to keep track of numbers being used
We run for loop to on number array and check if the Current Number (which in our case will always be New and Greater then previous ones) when divided by numbers in numArr leaves a remainder of 0.
If Remainder is 0, we add 1 to the counter.
Since we are already ignoring 1, the max number of counter for a prime number should be 1 which means only divisible by itself (only because we are ignoring it being divisible by 1)
Hence if counter is equal to 1, it confirms that the number is prime and we add it to the primeNumArr
And that's it. This will give you all prime numbers within your range.
PS: This code is written on current version of swift
Optimised with less number of loops
Considered below conditions
Even Number can not be prime number expect 2 so started top loop form 3 adding 2
Any prime number can not multiplier of even number expect 2 so started inner loop form 3 adding 2
Maximum multiplier of any number if half that number
var primeNumbers:[Int] = [2]
for index in stride(from: 3, to: 100, by: 2) {
var count = 0
for indexJ in stride(from: 3, to: index/2, by: 2) {
if index % indexJ == 0 {
count += 1
}
if count == 1 {
break
}
}
if count == 0 {
primeNumbers.append(index)
}
}
print("primeNumbers ===", primeNumbers)
I finally figured it out lol, It might be not pretty but it works haha, Thanks for everyone's answer. I'll post what I came up with if maybe it will help anyone else.
for n in 2...100 {
if n % 2 == 0 && n < 3{
print(n)
} else if n % 3 == 0 && n > 6 {
} else if n % 5 == 0 && n > 5 {
} else if n % 7 == 0 && n > 7{
} else if n % 2 == 1 {
print(n)
}
}

gnuplot: how to sum over an arbitrary list

For gnuplot, I have a large list of (randomly generated) numbers which I want to use as indices in a sum. How do I do it?
Here is what I mean. Let's say the list of numbers is
list = [81, 37, 53, 22, 72, 74, 44, 46, 96, 27]
I have a function
f(x,n) = cos(n*x)
I now want to plot the function, on the interval (-pi,pi) which is the sum of the f(x,n) as n runs through the numbers in list.
If you can control how your list looks like, try the following:
num = 10
# Let the numbers be in a space separated string.
# We can access the individual numbers with the word(string, index) function.
list = "81 37 53 22 72 74 44 46 96 27"
f(x,n) = cos(n*x)
set terminal pngcairo
set output "sum_cos.png"
set xrange [-pi:pi]
set samples 1000
# Build the plot command as a macro.
plt_cmd = ""
do for [n=1:num] {
plt_cmd = sprintf("%s + f(x,%s)", plt_cmd, word(list,n))
}
# Check what we have done so far.
print plt_cmd
titlestring = "{/Symbol S} cos(n_i*x), i = 1 ...".num
# Finally plot the sum by evaluating the macro.
plot #plt_cmd title titlestring
This is the result:

Check a multiple in Swift?

I am trying to find the odd numbers and a multiple of 7 between a 1 to 100 and append them into an array. I have got this far:
var results: [Int] = []
for n in 1...100 {
if n / 2 != 0 && 7 / 100 == 0 {
results.append(n)
}
}
Your conditions are incorrect. You want to use "modular arithmetic"
Odd numbers are not divisible by 2. To check this use:
if n % 2 != 0
The % is the mod function and it returns the remainder of the division (e.g. 5 / 2 is 2.5 but integers don't have decimals, so the integer result is 2 with a remainder of 1 and 5 / 2 => 2 and 5 % 2 => 1)
To check if it's divisible by 7, use the same principle:
if n % 7 == 0
The remainder is 0 if the dividend is divisible by the divisor. The complete if condition is:
if n % 2 != 0 && n % 7 == 0
You can also use n % 2 == 1 because the remainder is always 1. The result of any mod function, a % b, is always between 0 and b - 1.
Or, using the new function isMultiple(of:, that final condition would be:
if !n.isMultiple(of: 2) && n.isMultiple(of: 7)
Swift 5:
Since Swift 5 has been released, you could use isMultiple(of:) method.
In your case, you should check if it is not multiple of ... :
if !n.isMultiple(of: 2)
Swift 5 is coming with isMultiple(of:) method for integers , so you can try
let res = Array(1...100).filter { !$0.isMultiple(of:2) && $0.isMultiple(of:7) }
Here is an efficient and concise way of getting the odd multiples of 7 less than or equal to 100 :
let results: [Int] = Array(stride(from: 7, through: 100, by: 14))
You can also use the built-in filter to do an operation on only qualified members of an array. Here is how that'd go in your case for example
var result = Array(1...100).filter { (number) -> Bool in
return (number % 2 != 0 && number % 7 == 0)
}
print(result) // will print [7, 21, 35, 49, 63, 77, 91]
You can read more about filter in the doc but here is the basics: it goes through each element and collects elements that return true on the condition. So it filters the array and returns what you want

How to return an array with unhappy numbers removed?

I'm quite new to using MATLAB, and am still trying to understand how to make this particular function. I understand the formula for performing this on paper, but I'm having trouble translating it into the required MATLAB syntax.
How would a function be written such that it takes an array of numbers, and returns that array with unhappy numbers removed i.e. only happy numbers remaining?
EDIT - Proving and input and output
Input:
array = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,
41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
Output:
array = [7, 13, 19, 23, 31, 79, 97]
A happy number is such that a number's squared digits summed eventually equal to 1, or continue the process indefinitely as seen here.
I've written a small function (which might be further improved) to test the "happines" of a number.
Current version only works with scalar and one dim. array.
Input: the scalar or array to be tested
Output:
1) an index: happy (1) unhappy(0)
2) the list of happy number within the input set
3) the list of unhappy number within the input set
Running the function with the input specified in the question, the function returns:
function [is_happy,h_array,unh_array]=happy_number(in_val)
%
% Output:
% is_happy: 1 ==> the numberis happy
% 0 ==> the numberis unhappy
% h_array: happy numbers within input
% unh_array: unhappy numbers within input
%
% Input validity check (to be improved)
s=size(in_val);
if(iscell(in_val) || isstr(in_val) || isstruct(in_val) ...
|| ~find(s,1) || length(s) >= 3 || sum(floor(in_val)-in_val) ~= 0)
error('Only scalar or 1 dim array supported')
end
% Vars initialization
h_array=[];
unh_array=[];
h_array_cnt=1;
unh_array_cnt=1;
h_unh_cnt=1;
% Loop through input number
for i=1:length(in_val)
seq=[];
n=in_val(i);
seq_cnt=1;
seq(seq_cnt)=n;
% Test if the number is happy
while(n ~= 1 && n ~= 4)
% Decompose the number in its digits
sn=num2str(n);
nv=str2num(sn(:));
seq_cnt=seq_cnt+1;
seq(seq_cnt)=sum(nv.^2);
n=seq(seq_cnt);
end
% Set and display results
if(n == 1)
disp(['Number ' num2str(seq(1)) ' is HAPPY'])
is_happy(h_unh_cnt)=1;
h_unh_cnt=h_unh_cnt+1;
h_array(h_array_cnt)=seq(1);
h_array_cnt=h_array_cnt+1;
else
disp(['Number ' num2str(seq(1)) ' is UNHAPPY'])
is_happy(h_unh_cnt)=0;
h_unh_cnt=h_unh_cnt+1;
unh_array(unh_array_cnt)=seq(1);
unh_array_cnt=unh_array_cnt+1;
end
end
Hope this helps.
If you have the index of your unhappy numbers. You can remove them by writing :
array(unhappy_index) = [];
If you do not have the unhappy index, you can find them by using the followng command:
find()