Find equal pentagonal and square number

38 ビュー (過去 30 日間)
Shoandeep Radhakrishnan
Shoandeep Radhakrishnan 2021 年 9 月 9 日
コメント済み: DGM 2021 年 9 月 14 日
A pentagonal number is defined by p(n) = (3*n^2 – n)/2, where n is an integer starting from 1. Therefore, the first 12 pentagonal numbers are 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, 176 and 210.
A square number is defined by s(n) = n2, where n is an integer starting from 1. Therefore, the first 12 square numbers are 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, and 144.
From the above example, the number 1 is considered 'special' because it is both a pentagonal (p=1) and a square number (s=1). Determine the 3rd 'special' number (i.e. where p=s) assuming the number 1 to the be first 'special' number.
Does anyone knows how to solve this cause i am lost
  6 件のコメント
Jan
Jan 2021 年 9 月 14 日
@DGM: "when you're one person with 30-45 minutes to walk 20 distracted freshmen through a crash course in writing a couple simple MATLAB scripts"
I do agree. In this situation clear all is not the core problem, but "crash course in 45 minutes". If you have a very short time only to teach the basics, I still think it is worth not to teach anything, which must be taken back in the following hours. If I want to save time, I'd omit to mention scripts and claim that a Matlab file starts with keyword "function ...".
DGM
DGM 2021 年 9 月 14 日
I can agree with that.

サインインしてコメントする。

採用された回答

Jan
Jan 2021 年 9 月 9 日
This sounds like a homework question. Then the standard way is that you post, what you have tried so fas and ask a specific question.
You can create a list of the pentagonal numbers for the first million natural numbers:
n = 1:1e6;
n2 = n .^ 2;
n5 = (3 * n2 - n) / 2;
Now find the elements which occur in both vectors. See:
doc intersect
doc ismember
  1 件のコメント
Shoandeep Radhakrishnan
Shoandeep Radhakrishnan 2021 年 9 月 9 日
Ahh Alright Thank you so much!!

サインインしてコメントする。

その他の回答 (2 件)

DGM
DGM 2021 年 9 月 9 日
編集済み: DGM 2021 年 9 月 9 日
This is a rather brute force method, but it still only takes 1.5ms to find the third match on my dumpster PC.
n = 1:10000;
p = (3*n.^2 - n)/2;
s = n.^2;
p(ismember(p,s))
ans = 1×3
1 9801 94109401
I imagine a symbolic solution might be more elegant, but I'll leave that to someone who uses the symbolic toolbox more than I do.
  1 件のコメント
Shoandeep Radhakrishnan
Shoandeep Radhakrishnan 2021 年 9 月 9 日
Ahh Alright! Thank you so much :D

サインインしてコメントする。


Jan
Jan 2021 年 9 月 10 日
編集済み: Jan 2021 年 9 月 10 日
And a two-liner:
n = 1:10000;
find(any(((3*n.^2 - n)/2) == (n.^2).'))
Matlab can be very elegant. Do you understand the details of this solution?
  1 件のコメント
Shoandeep Radhakrishnan
Shoandeep Radhakrishnan 2021 年 9 月 14 日
YEa Thank you so much!!!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeEntering Commands についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by