## Prime numbers (C ++) without using loops

Is there a way to create code that checks whether the number entered is a prime number or not without using loops?

``````#include
using namespace std;
int main()
{
int n, i;
bool isPrime = true;
cout << "Enter a positive integer: ";
cin >> n;
for(i = 2; i <= n / 2; ++i)
{
if(n % i == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
cout << "This is a prime number";
else
cout << "This is not a prime number";
return 0;
}
``````

Code from another website

Cheers ~

## beginner – Location of prime numbers with use of limited prime numbers

I am looking for general comments on how to improve this code. At the time I wrote the program, it started without functions, which makes adaptation very difficult. When I separated the program into functions, it became very repetitive. How to cope?

``````"""
A program for comparrison of triangulation (wave or skipping stones, not sure what to call it?) to division by same limited known prime numbers
as how well they spot new ones
"""

from math import sin #only for wave
from math import pi #period and period displacement of wave
from math import sqrt #On the top of my head estimate of average overlapping multiplied waves. sin(pi/4) = sqrt(2)/2
from math import e
from statistics import mean
def Primer(number, numbers):#Generates primes by modulus for every prime in numbers
iteration = 0
while number % numbers(iteration) != 0: # as long as number modulus prime givesw remainder it keeps dividing
iteration +=1
if iteration == len(numbers):# Every former prime in list of primes hass been divided with remainder
return number
else:
pass
def Triangulation(numbers, x): #or skipping stone analogy. I dont understand this in combinatorics. prime 2 wave skips every other, prime every third and so on
wave = 1
for number in numbers:
wave *= abs(sin(x*pi/number)*2/sqrt(2)) # sqrt(2)/2 * 2/swrt(2) = 1 to keep the wave around zero
if wave > 1:
return wave, x
else:
return "","" #cant unpack None type
primes = (2,3)
exponent = 3
limit = int(10**exponent)
window = (0, limit)
triangulation = ()
true = ()
false = ()
primes_for_triangulation = ()
use_primes_up_to = e**(exponent)
primes_in_window = ()
wave_amplitude = ()
true_wave_amplitude = ()
false_wave_amplitude = ()
primes_by_limited_division = ()
false_quotient = ()
true_quotient = ()
for number in range(len(primes)+2, limit, 1):
possibly_prime = Primer(number, primes)#feeds primer with numbers and past primes...
if type(possibly_prime) == int:
primes.append(possibly_prime)#when prime is found it gets put into cycles
for prime in primes:#creating a list from part of list
if prime < use_primes_up_to:
primes_for_triangulation.append(prime)
else:
pass
if prime >= window(0) and prime < window(1):#remenant from when window was different than zero to limit
primes_in_window.append(prime)
else:
pass
for x in range(window(0), window(1), 1):# For every x down the number line the skipping stones hops over unkown primes diving into previous ones...
possibly_wave_amplitude, possibly_triangulated = (Triangulation(primes_for_triangulation, x))
if type(possibly_triangulated) == int: #... if its int theyre in the air
triangulation.append(possibly_triangulated)
wave_amplitude.append(possibly_wave_amplitude)
for tri in range(0, len(triangulation), 1):#seperating 2 list into 4 by true or false
if triangulation(tri) in primes:
true.append(tri)
true_wave_amplitude.append(wave_amplitude(tri))
else:
false.append(tri)
false_wave_amplitude.append(wave_amplitude(tri))
for number in range(4, limit, 1): #looking for primes...
limited_division = Primer(number, primes_for_triangulation)#...by limited prime list
if type(limited_division) == int:
primes_by_limited_division.append(limited_division)
for possibly_prime in primes_by_limited_division:#seperating a list into 2 by true or false
if possibly_prime in primes:
true_quotient.append(possibly_prime)
else:
false_quotient.append(possibly_prime)
#print out dosent handle zero
print("LIMITED DIVISION AND TRIANGULATION UP TO LIMIT", limit)
print("Primes up to ", use_primes_up_to, " were used to triangulate and to do limited division")
print("How many limited true divided ", len(true_quotient))
print("How many limited faulty divided ", len(false_quotient))
print("True per false ", len(true_quotient)/len(false_quotient))
print("Triangulate in window with lower bound being ", window(0), " and upper bound being limit ", window(1))
print("How many triangulated to be primes = ", len(triangulation))
print("Triangulated per window span = ", len(triangulation)/(window(1)-window(0)))
print("How many triangulated per primes in window ", len(triangulation)/len(primes_in_window)) #Zero division
print("How many Falesly triangulated ", len(false))
print("How many truely triangulated ", len(true))
print("True per false ", len(true)/len(false)) #Zero division
print("Mean of true wave amplitude ", mean(true_wave_amplitude))
print("Mean of false wave amplitude ", mean(false_wave_amplitude))
print("Largest true wave amplitude ", max(true_wave_amplitude))
print("Largest false wave amplitude ", max(false_wave_amplitude))
print("Smallest true wave amplitude ", min(true_wave_amplitude))
print("Smallest flase wave amplitude ", min(false_wave_amplitude))
print("n Wave amplitude of falsely triangulated nn", false_wave_amplitude)
print("n Wave amplitude of truely triangulated nn", true_wave_amplitude)

``````

Also specifically for how to lighten code by managing lists other than with the for?

Here for example

``````
for tri in range(0, len(triangulation), 1):#seperating 2 list into 4 by true or false
if triangulation(tri) in primes:
true.append(tri)
true_wave_amplitude.append(wave_amplitude(tri))
else:
false.append(tri)
false_wave_amplitude.append(wave_amplitude(tri))

``````

How to manage the separate cant Nothing other than the return of two chains?

``````
def Triangulation(numbers, x): #or skipping stone analogy. I dont understand this in combinatorics. prime 2 wave skips every other, prime every third and so on
wave = 1
for number in numbers:
wave *= abs(sin(x*pi/number)*2/sqrt(2)) # sqrt(2)/2 * 2/swrt(2) = 1 to keep the wave around zero
if wave > 1:
return wave, x
else:
return "","" #cant unpack None type

``````

How not to get the unfilled list with type None or how to easily delete the type None?

``````    for number in range(4, limit, 1): #looking for primes...
limited_division = Primer(number, primes_for_triangulation)#...by limited prime list
if type(limited_division) == int:
primes_by_limited_division.append(limited_division)

``````

## vba – Retrieve the status of a list of FedEx tracking numbers

Context

If you buy something in our establishment, you will receive a box with a shipping label. The two main numbers he will have are a FedEx tracking number and one carton number. For cartons that are not already in a manifested or billed condition in our warehouse management system, it is necessary to check the FedEx website to determine if a carton has left our building. The statuses I would be looking for on the FedEx website are "picked up", "in transit" and "delivered".

The FedEx website classifies tracking numbers in different sections depending on the state. As of June 2019, looking at the html elements, there were 19 sections. To clarify, if you have a list of numbers you are looking for, the website takes the tracking numbers out of order, so that when you compare your list with the website, you scroll up and down by constantly trying to figure out which section the number is in. In most of my uses, there were only 2 or 3 sections used, but it always required a constant from top to bottom when comparing back and forth.
Okay, so you have the status on the website, you match this 10-digit tracking number to the one on your list, then you can highlight the associated carton number. The cardboard number in transit is what we need, so we can process the cardboard number.

Another problem is that the FedEx website only allows you to paste 30 tracking numbers at a time. So if you do this manually for 1000 tracking numbers, you have to sort of split your list into 30 pieces at a time, then paste them into the website, do your research back and forth by comparing the 39; exercise, then do it 33 more times. It will take a long time, and due to the nature of the process and the length of the numbers, it will be very prone to errors. You might even give up because it's so tedious.

Goal

I had a column of FedEx tracking numbers. In another column, I had a list of associated carton numbers. My goal was to have a third column showing FedEx status. On this third column, I applied conditional formatting of the green fill color to highlight the text containing "picked up", "in transit", "delivered". I could then filter on the green color and I would have a list of carton numbers that had left the building. It was the end of my coding. From there, I could take this list and paste it into our warehouse management system to do the necessary processing.

Step-by-step procedure:

Start on shData (1.User Input) by pasting the tracking and cardboard numbers as follows:

The code will generate links where each link concatenates up to 30 tracking numbers together, like this:

The code will run through the links, opening Internet Explorer, Ctrl + A (selecting all) and Ctrl + C (copying), then returning to shPastes (3. Pastes) and pasting the results. Some filtering will occur, so as not to recover all the unnecessary text.

Finally, in shStatus (4. Status), the filtered pasta will form a table and an index match will display the associated box. A green filter on the status column will only display cartons in transit, like this:

A few notes

This is my first publication. I have been programming in VBA for less than a year. I am a beginner. I don't know how to make tables. Error handling is new to me. I installed RubberDuck. This code is actually a rewrite of my original, which was a horrible code, but it worked and saved me a ton of time at work. I am looking for a review, so I can still improve. Thank you for your time.

Code Explorer:

Worksheet code name: `shData`

``````'@Folder("FedEx_Tracking")
Option Explicit

'@Ignore ProcedureNotUsed
Private Sub StartTrackingButton_Click()
If DoSimpleChecks = "Not Ready" Then
Exit Sub
End If
ProgressIndicatorForm.Show

End Sub

Private Function DoSimpleChecks() As String

DoSimpleChecks = vbNullString
'//Check if data has been pasted
With shData
If .Range("A2").Value = vbNullString Or .Range("B2").Value = vbNullString Then
MsgBox "Please paste in the following data:" & vbNewLine & vbNewLine & "TRACKING number into A2" & vbNewLine & "CARTON number into B2", vbInformation, "Required Data"
.Activate
.Range("A2").Select
Else
End If
End With

End Function

'@Ignore ProcedureNotUsed
Private Sub ClearOldDataButton_Click()
Call ClearSheetDataForNewUse
End Sub

Private Sub ClearSheetDataForNewUse()

With shData
.Columns("A:E").ClearContents
.Range("A1").Value = "Paste Tracking"
.Range("B1").Value = "Paste Carton"
'//Move the cursor here for the user to begin pasting here
.Range("A2").Select
End With

End Sub
``````

Form: `ProgressIndicatorForm`

``````'@Folder("FedEx_Tracking")
Option Explicit

Private Sub UserForm_Activate()
Call TopMost
End Sub
``````

Module: `m_fedex_tracking`

``````Attribute VB_Name = "m_fedex_tracking"
'@Folder("FedEx_Tracking")
Option Explicit

Private Enum DataColumns
(Paste Tracking) = 1                         'A
(Paste Carton) = 2                           'B
(Trimmed Tracking) = 3                       'C
End Enum

End Enum

Public Sub TopMost()

On Error GoTo CleanFail
Dim beginSeconds As Single
beginSeconds = Timer()

Call LudicrousMode(True)
Call FormatColumnsAthruD
Call TrimTextofTracking
Call LoopOpenIEandSelectAllCopyPaste
Call SetEntireRangeOfResultingPastes
Call CopyFilteredPastesToStatusesSheet
Call CreateTableofStatuses
Call CreateTableForTrackingCartonLookup
Call IndexMatchToGetAssociatedCarton
Call SetConditionalFormattingStatusColumnofStatusSheet
Call FormatColumnWidthsOfStatusSheet
Call FilterResultsOfStatusSheet
Call TakeUserHereAtTheEnd

CleanExit:
Call LudicrousMode(False)
Dim endSeconds As Single
endSeconds = Timer()
MsgBox "Time taken to complete:" & vbNewLine & endSeconds - beginSeconds & " seconds", vbInformation, vbNullString
Exit Sub
CleanFail:
MsgBox Err.Number & vbTab & Err.Description, vbCritical, "Error"
Resume CleanExit

End Sub

Private Sub LudicrousMode(ByVal Toggle As Boolean)
'Adjusts Excel settings for faster VBA processing
Application.ScreenUpdating = Not Toggle
Application.EnableEvents = Not Toggle
Application.EnableAnimations = Not Toggle
Application.DisplayStatusBar = Not Toggle
Application.Calculation = IIf(Toggle, xlCalculationManual, xlCalculationAutomatic)
End Sub

Private Sub FormatColumnsAthruD()

Const HEADER_ROW_NUM As Long = 1
'//Format columns A:C as text, not D, because I might want it to be a clickable link in the future
shData.Columns("A:C").NumberFormat = "@"

'//If there is old generated data, clear it
shData.Columns("C:D").ClearContents

'TODO: Take a look whether using private enum for columns is even necessary for this project scope with such few headers _
it was mainly done this way because I had never used private enums before.

'//Re-write the column headers of the cleared columns
shData.Cells(HEADER_ROW_NUM, DataColumns.(Trimmed Tracking)).Value = "Trimmed Tracking"

End Sub

Private Function GetLastDataRow(ByVal xlSheet As Worksheet, Optional ByVal columnLetter As String = "A") As Long
'Function obtained from here: https://codereview.stackexchange.com/questions/43290/importing-data-from-an-external-excel-sheet
'RubberDuck inspection quacks: "Argument with incompatible object type" every time the function is used, but no errors are present when running the code.

'//a worksheet's codename is passed to xlSheet;
GetLastDataRow = xlSheet.Range(columnLetter & xlSheet.Rows.Count).End(xlUp).Row

End Function

Private Sub TrimTextofTracking()

Dim lastPasteTrackingRow As Long
lastPasteTrackingRow = GetLastDataRow(shData, "A")

'//Use trim function to remove leading or trailing spaces, otherwise it will mess up lookups; _
write to a new column
Dim i As Long
For i = 2 To lastPasteTrackingRow
With shData
.Cells(i, DataColumns.(Trimmed Tracking)).Value = WorksheetFunction.Trim(.Cells(i, DataColumns.(Paste Tracking)))
End With
Next i

'shData.Columns(DataColumns.(Trimmed Tracking)).EntireColumn.AutoFit

End Sub

'Const OLD_PREFIX_FOR_FEDEX_LINK As String = "https://www.fedex.com/apps/fedextrack/index.html?tracknumbers="
Const PREFIX_FOR_FEDEX_LINK As String = "https://www.fedex.com/apps/fedextrack/?action=track&trackingnumber="
Const SUFFIX_FOR_FEDEX_LINK As String = "&cntry_code=us&locale=en_US"

'//This does not include the 1st tracking number at the start of each range. _
If included, it would equal 30, which is the max number of tracking numbers that can be concatenated into a link, set by FedEx.com
Const ADD_TO_FIRST_STRING As Long = 29

'//First tracking number of link2 is 30 numbers after the first tracking number of link1

Dim lastTrimmedRow As Long
lastTrimmedRow = GetLastDataRow(shData, "C")

'//Ideally 30 Tracking numbers concatenated to form a link, then for example:& _
Dim i As Long
For i = 2 To lastTrimmedRow Step ROWS_BETWEEN_GENERATED_LINKS
concatRange(shData.Range("C" & i & ":C" & i + ADD_TO_FIRST_STRING), ",") & _
Next i

End Sub

Public Function concatRange(ByVal myRange As Range, ByVal mySeperator As String) As String
'Code came from some website
Dim cell As Range
Dim currentRange As String
Dim r As String

currentRange = vbNullString

For Each cell In myRange
If cell.Value <> vbNullString Then
r = cell.Value & mySeperator
currentRange = currentRange & r
End If
Next cell

currentRange = Left\$(currentRange, Len(currentRange) - Len(mySeperator))
concatRange = currentRange

End Function

'//Filter column, no blanks
shData.Range("D1").AutoFilter Field:=4, criteria1:="<>", Operator:=xlFilterValues

'//Get range & copy

'//Paste selection to new sheet

'//Remove filter
shData.Range("D1").AutoFilter

'//Exit out of cut/copy mode
Application.CutCopyMode = False

End Sub

Private Sub ClearAndFormatSheetPastesAsText()

With shPastes
.Cells.ClearContents
.Cells.NumberFormat = "@"
End With

End Sub

Private Sub LoopOpenIEandSelectAllCopyPaste()

Call ClearAndFormatSheetPastesAsText

With shPastes
'//Set the first place to begin pasting; This has to be here for the rest of the sub to work.
.Activate
.Range("A1").Select
End With

Dim IEbrowser As Object
Set IEbrowser = CreateObject("InternetExplorer.Application")

With IEbrowser
.Visible = True

DoEvents
Loop

'//this additional wait is necessary on FedEx website to ensure page is fully loaded
Application.Wait (Now + TimeValue("00:00:04"))

'// SelectAll (Ctrl+A)
.ExecWB 17, 0
Application.Wait (Now + TimeValue("00:00:01"))
'// Copy selection (Ctrl+C)
.ExecWB 12, 2
End With

'//Paste as Match destination formatting & _
FormatHTML, but with no HTMLFormatting is absolutely necessary for pasting from FedEx tracking website & _
because it keeps necessary table formatting. Tracking no., status, etc. are each kept in same row but separate columns, & _
which makes it possible to filter the results. Pasting as text or values does not work!

With shPastes

'//Set starting point for next paste
.Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).Select
End With

'//'https://www.excel-easy.com/vba/examples/progress-indicator.html _
if there are 10 links, it will show 10% complete after the 1st link
Dim percentComplete As Single
progress percentComplete

IEbrowser.Quit
Set IEbrowser = Nothing
End Sub

Private Sub SetEntireRangeOfResultingPastes()
'//Find position of last cell
Dim lastPastesRow As Long
lastPastesRow = GetLastDataRow(shPastes, "A")
'TODO: redo this particular lastColumn variable to get rid of ActiveCell
Dim lastColumn As Long
lastColumn = ActiveCell.SpecialCells(xlLastCell).column

'//Set range
Dim EntireRangeOfPastes As Range
Set EntireRangeOfPastes = shPastes.Range("A1", shPastes.Cells(lastPastesRow, lastColumn))

'//Filter range on Column A ascending (A to Z), so the tracking numbers are at the top
EntireRangeOfPastes.AutoFilter

'//Remove duplicates on Column A

End Sub

Private Sub CopyFilteredPastesToStatusesSheet()
'//Find position of last cell
Dim lastPastesRow As Long
lastPastesRow = GetLastDataRow(shPastes, "A")
'TODO: redo this particular lastColumn variable to get rid of ActiveCell
Dim lastColumn As Long
lastColumn = ActiveCell.SpecialCells(xlLastCell).column

'//Set range
Dim filteredPastes As Range
Set filteredPastes = shPastes.Range("A1", shPastes.Cells(lastPastesRow, lastColumn))

'//Clear entire sheet, where I will be pasting to, along with clearing any conditional formatting
With shStatus
.Cells.ClearContents
.Cells.FormatConditions.Delete
.Columns.Range("B:B", "B:B").NumberFormat = "@"
End With

'//Copy & Paste
filteredPastes.Copy
With shStatus
.Range("B1").PasteSpecial
.Range("A1").Value = "Carton"
End With

End Sub

Private Sub CreateTableofStatuses()
'//Since I have a lookup in column Z (column 26), & _
Set this first table to have a max of 10 columns ending in column J, so there isn't a possiblity of a table overlap error
Const FIRST_TABLE_LAST_COLUMN As Long = 10

'//Get position of lastTrackingRow
Dim lastTrackingRow As Long
lastTrackingRow = GetLastDataRow(shStatus, "B")

'//Create Table
shStatus.ListObjects.Add(xlSrcRange, shStatus.Range("A1", shStatus.Cells(lastTrackingRow, FIRST_TABLE_LAST_COLUMN)), , xlYes).Name = "tbl_FedEx"

With shStatus
'// Write/Overwrite Headers for first few columns in case there are no cartons with status found
.Range("A1").Value = "Carton"
.Range("B1").Value = "Tracking No. or Nickname"
.Range("C1").Value = "Status"
.Range("D1").Value = "Scheduled Delivery Date"
.Range("E1").Value = "Ship Date"
End With

End Sub

Private Sub CreateTableForTrackingCartonLookup()
'Copying the range from shData to shStatus seems unnecessary, but if I want, I can make a copy of shStatus and rename it or move it to another workbook for historical and sharing purposes. _
Sharing a single worksheet with all the info on it is easiest.

'//Set range of first four columns
Dim trackingCartonLookup As Range
Set trackingCartonLookup = shData.Range("A1").CurrentRegion

'//Copy & paste range far enough from the first table
trackingCartonLookup.Copy
shStatus.Range("Z1").PasteSpecial

'//Find position of last cell in range
Dim lastRow As Long
lastRow = shStatus.Range("Z1").CurrentRegion.Rows.Count
Dim lastColumn As Long
lastColumn = shStatus.Cells(1, shStatus.Columns.Count).End(xlToLeft).column

'//Create Table
shStatus.ListObjects.Add(xlSrcRange, shStatus.Range("Z1", shStatus.Cells(lastRow, lastColumn)), , xlYes).Name = "tbl_trackingCarton"

End Sub

Private Sub IndexMatchToGetAssociatedCarton()
Const MINIMUM_TABLE_ROWS As Long = 2
Const DOUBLE_QUOTE As String = """"
'//To display a message upon N/A, replace vbNullString with "text" (including the " " around text)
Const EXPLANATION_IF_NA As String = DOUBLE_QUOTE & vbNullString & DOUBLE_QUOTE

On Error GoTo CleanFail

With shStatus
'//Index Match
.Range("A2").Value = "=IFNA(INDEX(tbl_trackingCarton,MATCH((@(Tracking No. or Nickname)),tbl_trackingCarton(Trimmed Tracking),0),2)," & EXPLANATION_IF_NA & ")"

Continue:
'//To prevent error, Autofill down--only if the table has enough rows
If .Range("A1").CurrentRegion.Rows.Count > MINIMUM_TABLE_ROWS Then
.Range("A2").AutoFill Destination:=.Range("tbl_FedEx(Carton)")
End If

End With

'@Ignore LineLabelNotUsed
CleanExit:
Exit Sub

CleanFail:
If Err.Number = 1004 Then
Err.Clear
'// Win 7 32-bit, Excel 2010 32-bit VBA 6.5 gave this error until I changed the formula to this
shStatus.Range("A2").Value = "=INDEX(tbl_trackingCarton,MATCH(tbl_FedEx((#This Row),(Tracking No. or Nickname)),tbl_trackingCarton(Trimmed Tracking),0),2)"
Else
MsgBox Err.Number & vbTab & Err.Description, vbCritical, "Error"
Exit Sub
End If
GoTo Continue

End Sub

Private Sub SetConditionalFormattingStatusColumnofStatusSheet()
Const COLOR_GRANNY_APPLE As Long = 13561798  'Same as the Style "Good" fill color

Dim statusColumn As Range
Set statusColumn = shStatus.Range("tbl_FedEx(Status)")

With .Interior
.PatternColorIndex = xlColorIndexNone
.Color = COLOR_GRANNY_APPLE
End With
End With

With .Interior
.PatternColorIndex = xlColorIndexNone
.Color = COLOR_GRANNY_APPLE
End With
End With

With .Interior
.PatternColorIndex = xlColorIndexNone
.Color = COLOR_GRANNY_APPLE
End With
End With

End Sub

Private Sub FormatColumnWidthsOfStatusSheet()
With shStatus
'//Resize columns 'Carton', 'Tracking', & 'Status'
.Columns("A:A").ColumnWidth = 26
.Columns("B:B").ColumnWidth = 26
.Columns("C:C").ColumnWidth = 26
'//Autofit 'Paste Tracking', 'Paste Carton', & 'Trimmed Tracking' columns
.Range("Z:Z", "AB:AB").EntireColumn.AutoFit
End With
End Sub

Private Sub FilterResultsOfStatusSheet()
Const COLOR_GRANNY_APPLE As Long = 13561798
With shStatus
'//Filter out the blanks in column 1 - disabled for now
'.ListObjects("tbl_FedEx").Range.AutoFilter Field:=1, Criteria1:="<>"

'//Filter on the green color
.ListObjects("tbl_FedEx").Range.AutoFilter Field:=3, criteria1:=COLOR_GRANNY_APPLE, Operator:=xlFilterCellColor
End With
End Sub

Private Sub TakeUserHereAtTheEnd()

With shStatus
'//Navigate the user here to view the results
.Activate
.Range("C1").Select
End With
End Sub

Private Sub progress(ByVal percentComplete As Single)
'Progress indicator code from here: https://www.excel-easy.com/vba/examples/progress-indicator.html
ProgressIndicatorForm.Text.Caption = percentComplete & "% Completed"
ProgressIndicatorForm.Bar.Width = percentComplete * 2

DoEvents

End Sub
``````

## A very nice factorization of the numbers \$ 2 ^ {2n} -1 \$:

Mersenne prime and factorization of the numbers of the form $$2 ^ n -1$$ are my object of interest currently. I came across a neat pattern.

All form numbers $$2 ^ {2n} -1$$ or $$n in mathbb {N}$$ have a simple and fast factorization technique. Namely, the form numbers $$2 ^ {2n} – 1$$ factor in $$(2 ^ n – 1) cdot (2 ^ n + 1).$$

For example:
To take $$2 ^ 6-1 = 63$$ which can be represented as $$2 ^ {2 cdot 3} – 1 = 63$$. The factorization of 63 is $$(2 ^ 3 – 1) cdot (2 ^ 3 + 1) = 7 cdot 9 = 63.$$

Another example: To take $$2 ^ {12} -1 = 4095.$$
By this rule, $$2 ^ {12} – 1 = (2 ^ 6 -1) cdot (2 ^ 6 + 1) = 63 cdot 65$$.

I am not entirely sure if this is an existing mathematical fact that is well known, but I thought it was worth sharing.

## Contacts – Spreadsheet Automate Numbers Using AppleScript

It’s a bit long, but there you go…

Using AppleScript (vanilla, please), I want to automate the Numbers spreadsheet that I created for my wife's music lesson accounts (which she uses four times a year – she is the only user).

This is my first AppleScript project. I have found individual pieces that work partially and I would like to help put them together.

Script 1A and Script 1B should be combined into ONE Script, but I don't know how to do it.

Script 1 should only be run once, after opening the spreadsheet (manually), but Script 2 will be run for each student account, to generate an email (so approximately 25 times individually)

Script 2 should get information from script 1 – see below.

The overall sequence should be as follows:

1) The user ensures that the contacts are up to date on a laptop (Catalina) and manually opens the Accounts spreadsheet.
2) Run scripts 1A and 1B (which will be ONE script)
3) Fill in the details
4) Run script 2
5) Check and send (manually) an email.
6) Repeat from 3) for each student
——————————-

Script 1A

``````--returns Contacts group’s names and email addresses

set myList to ""
tell application "Contacts" to repeat with p in people in group "testGroup"
if emails of p is {} then
set e to ""
else
set e to value of email 1 of p
end if
set myList to myList & name of p & ":" & e & linefeed -- gives full names
end repeat
``````

(the result is for example…) (I don't know if this result is in an appropriate format…)

"Peter Pan: peterpan@gmail.com
Joe Bloggs: joebloggs@gmail.com
Molly Mouse: mollymouse@gmail.com
"
——————————-

Script 1B MUST USE the above items result in Script 1A, NOT the menuItems list below!

``````
set menuItems to {"Joe Bloggs", "Molly Mouse", "Peter Pan"}

tell application "Numbers"
activate
tell the first table of the active sheet of document 1
tell cell "A3"
-- Set the cell value to the first menu item required. This also selects the cell.
set value to item 1 of menuItems
-- THEN set the cell format. This causes the menu to adopt the value just set as a single item instead of having the three default items.
set the format to pop up menu
end tell
end tell
end tell

tell application "System Events"
tell application process "Numbers"
set frontmost to true
tell window 1
-- The inspector doesn't have to be visible, but its "Cell" pane does have to be selected. (?)
-- Adds the remaining items by clicking the "+" button and inputting the texts the required number of times.
repeat with i from 2 to (count menuItems)
click button 1 of group 1 of scroll area -1
end repeat
end tell
end tell
end tell
``````

——————————-

The user selects a name from the context menu, which now exists, and fills in the lesson details, fees, etc.

Then execute script 2 probably by pressing a key combination on the keyboard – the spreadsheet usually runs in full screen on the laptop, so a key combination would simplify things (not essential, but practical. I can assign the key combination).

——————————

Script 2

``````--Make an email, with a screen captured image of the spreadsheet page, ready to send to the address belonging to the selected name in the Pop-Up Menu

set thePath to POSIX path of (path to documents folder) & "IMAGE" & ".jpg"
do shell script "screencapture -R20,80,720,880 -tjpg" & space & quoted form of the thePath

tell application "Mail"
set myMessage to make new outgoing message
set subject of myMessage to "Music Lessons 1st Term"
set content of myMessage to " r r r "
set theAttachedImage to "Macintosh HD:Users:petehunter:Documents:IMAGE.jpg"
--
tell myMessage
make new to recipient at end of to recipients with properties {name:"peterpan@gmail.com “} —Fake name for test purposes! The Script must provide this/these names
make new attachment with properties {file name:theAttachedImage as alias}
end tell
--
activate -- brings Mail to front, for checking, and a manual send.
end tell
``````

——————————-

## haskell – Square all numbers one digit

Task: given a number (positive or negative), grid each digit of it and concatenate them, forming a resulting number.

For example:

9119 should become 811181 = 9 ^ 2 * 10 ^ 0 + 1 * 10 ^ 1 + 1 * 10 ^ 2 + 9 ^ 2 * 10 ^ 3
(-1) should become (-1)

My code:

``````-- convert a number to the list of digits
-- doesn't work with negative numbers
digs :: Integral x => x -> (x)
digs 0 = (0)
digs x = let
helper :: Integral x => x -> (x)
helper 0 = ()
helper n = helper (n `div` 10) ++ (n `mod` 10)
in
helper x

squareDigit :: Int -> Int
squareDigit n = let sign = signum n
digits = (digs (abs n))
digs_sq = map (^ 2) digits
-- we can't concat squares as they may have more then 1 digit
digs_sq_flat = map digs digs_sq >>= id
in
sign * foldl (acc x -> x + (acc * 10)) 0 digs_sq_flat
``````

Basically it works:

``````*SquareDigit> squareDigit 9119
811181
*SquareDigit> squareDigit (-9119)
-811181
``````

But maybe my solution can be made more elegant.

## gui design – How should I allow a user to enter a number where all the numbers are not valid?

I have an application where users have to configure certain machine parameters. One of these parameters is an integer percentage value, from 1 to 100. Unfortunately, for historical reasons, we are not able to support all values ​​from 1 to 100, so the range of options actually has all kinds of strange "holes", so it looks a bit more like this:

``````1, 2, 3, 4, *, 6, *, 8, *, 12, *, 16, 17, 18
``````

The holes are not evenly spaced, so we cannot reduce the input by giving users only the 1-50 options, or telling them to put only even numbers, or something smart like that.

Our current method is to use normal number entry and simply highlight the invalid numbers. This allows a user to easily see that their selection is incorrect, but it is difficult to see (a) Why this is wrong, and (b) what a correct number might look like.

This brings me to my question: which input element is best suited to help a user choose a valid number in a situation where all the numbers are not valid (but a finite number of numbers are valid)?

So far we have thought of:

• A conventional drop-down list
• There are still ~ 50 numbers to choose from, that's a lot of drop-down list options. It is also a little strange to use a drop-down list for a number.
• A datepicker component
• The user can enter their number (with validation) or select a valid number from a list of numbers displayed in a popup window under the entry.
• It would end up looking essentially like a grid of numbers – is it too much like a date picker?
• Steppers
• ~ 50 numbers is probably too numerous to be chosen easily with steppers, But once a number has been set, most of the adjustments are likely to be slightly up and down.

## javascript – Could someone explain to me what happens to the numbers and properties of my problematic objects in my project?

I made a mini application of stone, paper or scissors divided in two which are in two html files (main.html and options.html). The parts of this project are:

The "login" and the "game" itself

And I have 2 js files which are `main.js` and `box.js` also connected to two different html documents. In the main.js I have the objects of player 1, player 2 and the computer depending on whether the player wants to play against another player or against the computer.

Now what I do would be the part where one player plays with another player with the objects `playerOne` and `playerTwo`, which would be the objects of the players, and among its properties of each object are the property points of each object separately, this is where the points that each would earn would be placed. So the first problem is that when you play once, the player who wins at the start adds 1 point first but when he comes back he adds 2 points, for example, if player 1 wins twice, he has 3 points instead of just 2.

My second problem is that, as I said, my player 1 can play with another player or against the computer. The computer is therefore also an object called `computer` which has the property to play, like the object of player 2 which also has it, which is used to know by pressing the button to play against the computer or the other button for play against the player if you want to play against the computer or against a player. The problem here is that the game property of the two objects gives me the truth and only allows me to play against another player, when in reality what should happen is that if I Press the button `vs computer`, I should be playing against the computer and if I press `vs player`, should let me play against a player. Thanks in advance for reading this and apologizing in advance if I haven't developed enough.

``````"use strict";
//main.js
let playerOne= {
name: "",
turn: true,
option: "",
points: 0,
}

let playerTwo= {
name:"" ,
play: false,
turn: false,
option: "",
points: 0,
}

let computer= {
name: "Computer",
play: false,
turn: false,
option: "",
points: 0,
}

//selecting DOM elements

const firstInput= document.getElementById("input");
const firstPlusButton= document.getElementById("plusButton");
const compButton= document.getElementById("computer");
const playerButton= document.getElementById("player");
const secondInput= document.getElementById("input-two");
const secondPlusButton= document.getElementById("plusButton-two");

function calling(){
}

let data= playerOne.name= firstInput.value;
JSON.stringify(data);
console.log(playerOne.name);
console.log(playerOne);
if(typeof playerOne.name==="string"){
localStorage.setItem("playerOne",JSON.stringify(playerOne));
};
});

if(event.keyCode===13){
playerOne.name= firstInput.value;
console.log(playerOne.name);
if(typeof playerOne.name==="string"){
localStorage.setItem("playerOne",JSON.stringify(playerOne));
};
}
});

}

playerTwo.play=false;
computer.play=false;

if(computer.play===false){
playerTwo.play= true;
}

playerTwo.name= secondInput.value;

console.log(playerTwo.name);
console.log(playerTwo.play);
console.log(computer.play);

if(typeof playerTwo.name==="string"){
localStorage.setItem("playerTwo",JSON.stringify(playerTwo));
};

})

if(event.keyCode===13){
playerTwo.name= secondInput.value;

console.log(playerTwo.name);
console.log(playerTwo.play);
console.log(computer.play);

if(typeof playerTwo.name==="string"){
localStorage.setItem("playerTwo",JSON.stringify(playerTwo));
}

}
})

})
}

playerTwo.play= false;
computer.play= false;

console.log(playerTwo.play);
console.log(computer.play);

if(playerTwo.play===false){
computer.play=true;
localStorage.setItem("computer",JSON.stringify(computer));
}

})
};``````
``````

Rock paper or scissors

Rock paper or scissors set

+

+

Let's play people!

``````
``````"use strict";

//getting objects
let playerOne= JSON.parse(localStorage.getItem("playerOne"));
let playerTwo= JSON.parse(localStorage.getItem("playerTwo"));
let computer= JSON.parse(localStorage.getItem("computer"));

//game DOM elements
const playerName= document.getElementById("playerPoints");
const points= document.getElementById("points");
const enemyName= document.getElementById("enemyPoints");
const turnText= document.getElementById("turnText");
const rock= document.getElementById("rock");
const paper= document.getElementById("paper");
const scissors= document.getElementById("scissors");
const winnerText= document.getElementById("winner");
const playerText= document.getElementById("player");
const enemyText= document.getElementById("oponent");
const rockTwo= document.getElementById("rockTwo");
const paperTwo= document.getElementById("paperTwo");
const scissorsTwo= document.getElementById("scissorsTwo");

calling();

function calling(){
console.log(computer);
console.log(playerTwo);
if(playerTwo.play===true){
versusPlayer();
}else{
versusComputer();
}
}

function versusPlayer(){

playerName.innerHTML= playerOne.name;
enemyName.innerHTML= playerTwo.name;
playerText.innerHTML= playerOne.name;
enemyText.innerHTML= playerTwo.name;

if(playerOne.turn===true && playerOne.option===""){

playerOne.option= "rock";
playerOne.turn= false;
playerTwo.turn=true;
console.log(playerOne);
console.log(playerOne.turn);
if(playerTwo.turn===true ){
secondTurn();
}
});

playerOne.option= "paper";
playerOne.turn= false;
playerTwo.turn=true;
console.log(playerOne);
console.log(playerOne.turn);
if(playerTwo.turn===true ){
secondTurn();
}
});

playerOne.option= "scissors";
playerOne.turn= false;
playerTwo.turn=true;
console.log(playerOne);
console.log(playerOne.turn);
if(playerTwo.turn===true ){
secondTurn();
}

});
}

}

function secondTurn(){

playerTwo.option= "rock";
playerTwo.turn=false;
compareResults(playerOne.option,playerTwo.option);
});

playerTwo.option= "paper";
playerTwo.turn= false;
compareResults(playerOne.option,playerTwo.option);
});

playerTwo.option= "scissors";
playerTwo.turn= false;
compareResults(playerOne.option,playerTwo.option);
});

}

function compareResults(a,b){

switch(a + " " + b){
case "rock scissors":
case "scissors paper":
case "paper rock":
userOneWins(a,b);
break;
case "scissors rock":
case "paper scissors":
case "rock paper":
userTwoWins(a,b);
break;
default:
console.log("its a draw");
break
}
}

function userOneWins(a,b){
playerOne.points ++;
points.innerHTML= `\${playerOne.points}:\${playerTwo.points}`
if(a==="rock" && b==="scissors"){
winnerText.innerHTML= `Rock beats scissors. You won \${playerOne.name}`;
}
if(a==="scissors" && b==="paper"){
winnerText.innerHTML= `scissors cuts paper. You won \${playerOne.name}`
}
if(a==="paper" && b==="rock"){
winnerText.innerHTML= `Paper covers rock. You won \${playerOne.name}`
}
}

function userTwoWins(a,b){
playerTwo.points ++;
points.innerHTML= `\${playerOne.points}:\${playerTwo.points}`
if(a==="rock" && b==="scissors"){
winnerText.innerHTML= `Rock beats scissors. You won \${playerTwo.name}`;
}
if(a==="scissors" && b==="paper"){
winnerText.innerHTML= `scissors cuts paper. You won \${playerTwo.name}`
}
if(a==="paper" && b==="rock"){
winnerText.innerHTML= `Paper covers rock. You won \${playerTwo.name}`
}
}

function versusComputer(){

playerName.innerHTML= playerOne.name;
enemyName.innerHTML= computer.name;
playerText.innerHTML= playerOne.name;
enemyText.innerHTML= computer.name;

if(playerOne.turn===true && playerOne.option===""){

playerOne.option= "rock";
playerOne.turn= false;
computer.turn=true;
computerChoice();
});

playerOne.option= "paper";
playerOne.turn= false;
computer.turn=true;
computerChoice();

});

playerOne.option= "scissors";
playerOne.turn= false;
computer.turn=true;
computerChoice();
});
}
}

function computerChoice(){

let computerOptions=("rock","paper","scissors");

console.log(Math.random()*3)
}``````
``````

Rock paper or scissors

``````

0: 0

PlayerName

Computer

``````

Rock paper cover. You won player one!

View statistics

Statistics

<! -
Player1
0: 3
Player2
->

``````

## Sorting – How to put the 14 generated numbers line by line

How to generate the 14 numbers, line by line in the possibilities of the times?

```from random import randint import csv lista = list() jogos = list() print('-' * 36) print(' LOTO FÁCIL') print('-' * 36) quant = int(input('QUANTAS COMBINAÇÕES? ')) tot = 1 while tot <= quant: cont = 0 while True: num = randint(1,25) if num not in lista: lista.append(num) cont += 1 if cont >= 14: break lista.sort() jogos.append(lista(:)) lista.clear() tot += 1print(f'SORTEADOS {quant} JOGOS') for i, l in enumerate(jogos): print(f'Jogo {i}: {l}') n = int(quant) print('resultado {}'.format(n)) with open('teste1.csv','a') as arquivo: arquivo.write('resultado {}'.format(jogos(:))) lista_guardar = lista.append(arquivo) print(lista_guardar)```

## Microsoft Excel – add the data next to the same numbers

I have four columns of data as follows:

how can i add the numbers of 2 and 4 (1 2 3 4 the numbers of the columns if we consider) corresponding to the same values ​​in columns 1 and 3?

I mean I want to get these 4 columns into 2 columns where the values ​​of 2 and 4 columns are added when the values ​​of columns 1 and 3 are the same.