How can I spilt long integer number into pairs?

조회 수: 1 (최근 30일)
Abdulatif Alabdulatif
Abdulatif Alabdulatif 2014년 4월 17일
답변: Abdulatif Alabdulatif 2014년 4월 18일
Hi all,
I am working to solve the problem of finding the square root by using long division operation?
I know that there is a build in square root function but in my case I have to build my own function to find a square root by using a long division!
The first step of finding the square root by long division is decompose a number in two pairs and then work from that point.
ex: 1987 --> First pair(87), second pair(19) &&&& 198 --> First pair(98), second pair(1) as we should start pairing from right to left!
Could anyone help me to solve this issue? I wish if someone already has the code for perform square root by division! This will make live easier : )
Cheers,

채택된 답변

Niklas Nylén
Niklas Nylén 2014년 4월 17일
To split the integer x into pairs according to your description:
x = 12345
numDigitsInX = floor(log10(x))+1;
pairs = zeros(ceil(numDigitsInX/2),1);
for ii = 1:length(pairs)
pairs(ii) = mod(x,100);
x = (x-pairs(ii))/100;
end
  댓글 수: 2
Abdulatif Alabdulatif
Abdulatif Alabdulatif 2014년 4월 17일
Thanks for response! but I have difficulties to collect splitted data.
I built a function called test to try your function:
function [ ] = test()
q=[ ];
x = 12345;
numDigitsInX = floor(log10(x))+1;
pairs = zeros(ceil(numDigitsInX/2),1);
for ii = 1:length(pairs)
pairs(ii) = mod(x,100);
x = (x-pairs(ii))/100;
q = [q x];
end
dsip(q);
end
and the result was:
q =
123 1 0
which is not the result that I am looking for! I am looking for the following similar result:
q =
45 23 1
or the inverse like
q =
1 23 45
I am beginner in matlab, so it might me my fault of understanding this function.
wish you get my idea! : )
Niklas Nylén
Niklas Nylén 2014년 4월 17일
편집: Niklas Nylén 2014년 4월 17일
What is q? The variable 'pairs' contains the number pairs.
pairs =
45
23
1

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Abdulatif Alabdulatif
Abdulatif Alabdulatif 2014년 4월 18일
Ture : )
Thank you so much!

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by